├── .vscode └── settings.json ├── 01_Python_Fundamentals_and_Basics ├── 01_Brush_Up_Python.ipynb ├── 02_Object___Data_Structure.ipynb ├── 03_Control_Flow.ipynb ├── 04_Methods___Functions_P1.ipynb └── 05_Methods___Functions_P2.ipynb ├── 02_Python_Foundations ├── 01_Python_Get_Started.ipynb ├── 02_Python_DataTypes_Part__1.ipynb ├── 03_Python_DataTypes_Part__2.ipynb ├── 04_Python_Control_Flow.ipynb ├── 05_Python_OOPs.ipynb └── 06_Python_File_Handling.ipynb ├── 03_Python_Object_Oriented_Programming ├── 01_Object_Oriented_Py.ipynb ├── 02_OOPs_Python.ipynb └── module.py ├── 04_Python_Projects(Basic) ├── 01_Dice_Simulater.ipynb ├── 02_Python_Dictionary.ipynb ├── 03_The_Hangman.ipynb ├── 04_ProjPy_Tic-Tac-Toe_Game.ipynb ├── 04_ProjPy_Tic-Tac-Toe_Help.ipynb ├── 05_Railway_Ticketing_Sys.ipynb ├── 06_Rock_Paper_Scissor.ipynb ├── 07_The_perfect_Guess.ipynb ├── 08_Student_Library_System.ipynb └── 09_Snake_Water_Gun.ipynb ├── 05_Python_Projects(Intermediate) └── py.py ├── 06_Python_Projects(Advance) └── py.py ├── 07_Python_PracticeSet ├── 01_Prob_Py_Part_1.ipynb ├── 02_Prob_Py_Part_2.ipynb └── 03_Prob_Py_Part_3.ipynb ├── 08_Advance_Python ├── 01_Advance_Python_Part_1.ipynb ├── 02_Advance_Python_Part_2.ipynb └── module.py ├── 09_New_in_Python ├── 01_check_for_DS_lib_inst_N.ipynb ├── 02_Data_Structure_for_Data_Scientist.ipynb ├── 03_Speed_Comparison.ipynb ├── 04_Walrus_Operator.ipynb ├── 05_Match_Placeholder___regex.ipynb ├── 06_ args___kwargs .ipynb ├── 07_Python-Time-function.ipynb ├── 08_Function_Annotations.ipynb └── 09_dataclasses.ipynb ├── 10_Python_Miscellaneous ├── 01_List_Comprehension.ipynb ├── 02-Objects and Data Structures Assessment Test.ipynb ├── 03-Merging-two-dictionaries.ipynb ├── 04-Functions-Examples.ipynb ├── 05_File_handling.ipynb ├── 06_Python_OS Module_.ipynb └── 07_exception_handling.ipynb ├── README.md ├── _Python_Cheatsheets ├── 01_python Crash Course - Cheat sheet │ ├── 01_beginners_python_cheat_sheet_pcc.pdf │ ├── 02_beginners_python_cheat_sheet_pcc_lists.pdf │ ├── 03_beginners_python_cheat_sheet_pcc_dictionaries.pdf │ ├── 04_beginners_python_cheat_sheet_pcc_if_while.pdf │ ├── 05_beginners_python_cheat_sheet_pcc_functions.pdf │ ├── 06_beginners_python_cheat_sheet_pcc_classes.pdf │ ├── 07_beginners_python_cheat_sheet_pcc_files_exceptions.pdf │ └── 08_beginners_python_cheat_sheet_pcc_django.pdf ├── 02_Python For DataScience │ ├── 01_PythonForDataScience_Python.jpg │ ├── 02_PythonForDataScience_Pandas-1.jpg │ ├── 03_PythonForDataScience_Pandas-2.jpg │ ├── 04_PythonForDataScience_Numpy.jpg │ ├── 05_PythonForDataScience_Matplotlib.jpg │ ├── 06_PythonForDataScience_Bokeh.jpg │ ├── 07_PythonForDataScience_Seaborn.jpg │ ├── 08_PythonForDataScience_ImportingData.jpg │ ├── 09-PythonForDataScience_JupyterNoteBook.jpg │ ├── 10_PythonForDataScience_LinearAlzebra.jpg │ ├── 11_PythonForDataScience_Sckit-Learn.jpg │ └── 12_PythonForDataScience_Keras.jpg ├── Python 3 Cheat Sheet (credits - Laurent Pointal).pdf ├── Python DataQuest.jpg ├── Python Quick Guide.pdf ├── PythonCheatSheet-keywords.pdf └── Python_Intellipaat.pdf └── _img ├── Python_CS.png ├── carClass.png ├── py_hw.png └── train_berth_bp.jpg /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "workbench.colorCustomizations": { 3 | "activityBar.background": "#014d79"", 4 | "titleBar.activeBackground": "#0870ac42", 5 | "titleBar.activeForeground": "#c2c2c2" 6 | } 7 | } -------------------------------------------------------------------------------- /02_Python_Foundations/01_Python_Get_Started.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "01_Python_Get_Started.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [], 9 | "toc_visible": true, 10 | "authorship_tag": "ABX9TyNOyYcU5PsDtcKMANDYcNMT", 11 | "include_colab_link": true 12 | }, 13 | "kernelspec": { 14 | "name": "python3", 15 | "display_name": "Python 3" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "metadata": { 32 | "colab": { 33 | "base_uri": "https://localhost:8080/" 34 | }, 35 | "id": "sAdd98D3wswF", 36 | "outputId": "66a8b52c-5eb2-4291-df2c-7cee12a182e6" 37 | }, 38 | "source": [ 39 | "!python --version" 40 | ], 41 | "execution_count": null, 42 | "outputs": [ 43 | { 44 | "output_type": "stream", 45 | "text": [ 46 | "Python 3.6.9\n" 47 | ], 48 | "name": "stdout" 49 | } 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": { 55 | "id": "VfBleGs_wK0w" 56 | }, 57 | "source": [ 58 | "### __1. Hello World__\r\n", 59 | "\r\n" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "metadata": { 65 | "colab": { 66 | "base_uri": "https://localhost:8080/" 67 | }, 68 | "id": "btdDFvxxwgis", 69 | "outputId": "d26a3401-5b58-4efc-d480-e39081a72adc" 70 | }, 71 | "source": [ 72 | "print(\"Hello, World!\")" 73 | ], 74 | "execution_count": null, 75 | "outputs": [ 76 | { 77 | "output_type": "stream", 78 | "text": [ 79 | "Hello, World!\n" 80 | ], 81 | "name": "stdout" 82 | } 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": { 88 | "id": "JnneLwDqw9uL" 89 | }, 90 | "source": [ 91 | "### __2. Creating a Comment__" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "metadata": { 97 | "colab": { 98 | "base_uri": "https://localhost:8080/" 99 | }, 100 | "id": "Z1tUG1Vvw73v", 101 | "outputId": "dc55f8ba-c49a-41d4-dd5b-45933e340c77" 102 | }, 103 | "source": [ 104 | "# This is a comment\r\n", 105 | "print(\"Hello, World!\")\r\n", 106 | "\r\n", 107 | "print(\"Hello, World!\") #This is a comment\r\n", 108 | "\r\n", 109 | "# print(\"Hello, World!\")\r\n", 110 | "print(\"Cheers, Mate!\")\r\n", 111 | "\r\n", 112 | "\r\n", 113 | "# This is a comment\r\n", 114 | "# written in\r\n", 115 | "# more than just one line\r\n", 116 | "print(\"Hello, World!\")" 117 | ], 118 | "execution_count": null, 119 | "outputs": [ 120 | { 121 | "output_type": "stream", 122 | "text": [ 123 | "Hello, World!\n", 124 | "Hello, World!\n", 125 | "Cheers, Mate!\n", 126 | "Hello, World!\n" 127 | ], 128 | "name": "stdout" 129 | } 130 | ] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "metadata": { 135 | "id": "jZusUnv3xfeg" 136 | }, 137 | "source": [ 138 | "### __3. Python Variables__" 139 | ] 140 | }, 141 | { 142 | "cell_type": "markdown", 143 | "metadata": { 144 | "id": "dDU-HSuA4kH8" 145 | }, 146 | "source": [ 147 | "#### __a. Python Varible__ " 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "metadata": { 153 | "colab": { 154 | "base_uri": "https://localhost:8080/" 155 | }, 156 | "id": "sobCHuu5xkGC", 157 | "outputId": "9316e4cd-7738-485d-f988-c5af05a7f933" 158 | }, 159 | "source": [ 160 | "x = 5\r\n", 161 | "y = \"John\"\r\n", 162 | "print(x)\r\n", 163 | "print(y)" 164 | ], 165 | "execution_count": null, 166 | "outputs": [ 167 | { 168 | "output_type": "stream", 169 | "text": [ 170 | "5\n", 171 | "John\n" 172 | ], 173 | "name": "stdout" 174 | } 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "metadata": { 180 | "colab": { 181 | "base_uri": "https://localhost:8080/" 182 | }, 183 | "id": "ZsYS5crzxy7c", 184 | "outputId": "9e4056a2-31fe-44d0-89bd-977a898e82d4" 185 | }, 186 | "source": [ 187 | "x = str(3) # x will be '3'\r\n", 188 | "y = int(3) # y will be 3\r\n", 189 | "z = float(3) # z will be 3.0\r\n", 190 | "\r\n", 191 | "print(x)\r\n", 192 | "print(y)\r\n", 193 | "print(z)" 194 | ], 195 | "execution_count": null, 196 | "outputs": [ 197 | { 198 | "output_type": "stream", 199 | "text": [ 200 | "3\n", 201 | "3\n", 202 | "3.0\n" 203 | ], 204 | "name": "stdout" 205 | } 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "metadata": { 211 | "colab": { 212 | "base_uri": "https://localhost:8080/" 213 | }, 214 | "id": "1yGIhUcvx9Fy", 215 | "outputId": "48a49b73-26e4-430f-ffba-bd83ece1eb74" 216 | }, 217 | "source": [ 218 | "x = 5\r\n", 219 | "y = \"John\"\r\n", 220 | "print(type(x))\r\n", 221 | "print(type(y))" 222 | ], 223 | "execution_count": null, 224 | "outputs": [ 225 | { 226 | "output_type": "stream", 227 | "text": [ 228 | "\n", 229 | "\n" 230 | ], 231 | "name": "stdout" 232 | } 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "metadata": { 238 | "id": "K-jb67Y5yIo3" 239 | }, 240 | "source": [ 241 | "x = \"John\"\r\n", 242 | "# is the same as\r\n", 243 | "x = 'John'" 244 | ], 245 | "execution_count": null, 246 | "outputs": [] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "metadata": { 251 | "id": "dd2t5y3cyNwx" 252 | }, 253 | "source": [ 254 | "# Variable names are case-sensitive\r\n", 255 | "\r\n", 256 | "a = 4\r\n", 257 | "A = \"Sally\" # A will not overwrite a" 258 | ], 259 | "execution_count": null, 260 | "outputs": [] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": { 265 | "id": "QHzulaDf4uij" 266 | }, 267 | "source": [ 268 | "#### __b. Variable Names__" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "metadata": { 274 | "id": "GRybmSliycHA" 275 | }, 276 | "source": [ 277 | "# Legal variable names\r\n", 278 | "\r\n", 279 | "myvar = \"John\"\r\n", 280 | "my_var = \"John\"\r\n", 281 | "_my_var = \"John\"\r\n", 282 | "myVar = \"John\"\r\n", 283 | "MYVAR = \"John\"\r\n", 284 | "myvar2 = \"John\"" 285 | ], 286 | "execution_count": null, 287 | "outputs": [] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": { 292 | "id": "cAN0cCn2ynLx" 293 | }, 294 | "source": [ 295 | "```python\r\n", 296 | "# Illegal variable names\r\n", 297 | "\r\n", 298 | "2myvar = \"John\"\r\n", 299 | "my-var = \"John\"\r\n", 300 | "my var = \"John\"\r\n", 301 | "```" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "metadata": { 307 | "id": "9pT2EwXvy2j2" 308 | }, 309 | "source": [ 310 | "# Camel Case\r\n", 311 | "myVariableName = \"John\"\r\n", 312 | "\r\n", 313 | "# Pascal Case\r\n", 314 | "MyVariableName = \"John\"\r\n", 315 | "\r\n", 316 | "# Snake Case\r\n", 317 | "my_variable_name = \"John\"" 318 | ], 319 | "execution_count": null, 320 | "outputs": [] 321 | }, 322 | { 323 | "cell_type": "markdown", 324 | "metadata": { 325 | "id": "_AucN7PX40Aj" 326 | }, 327 | "source": [ 328 | "#### __c. Assign Multiple Values__" 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "metadata": { 334 | "colab": { 335 | "base_uri": "https://localhost:8080/" 336 | }, 337 | "id": "q92s2zsazK4T", 338 | "outputId": "eb927e6a-c964-4a12-db66-a56ad3ef6a93" 339 | }, 340 | "source": [ 341 | "# Assign Multiple Values\r\n", 342 | "\r\n", 343 | "x, y, z = \"Orange\", \"Banana\", \"Cherry\"\r\n", 344 | "print(x)\r\n", 345 | "print(y)\r\n", 346 | "print(z)\r\n", 347 | "\r\n", 348 | "# One Value to Multiple Variables\r\n", 349 | "\r\n", 350 | "a = b = c = \"Orange\"\r\n", 351 | "print(a)\r\n", 352 | "print(b)\r\n", 353 | "print(c)" 354 | ], 355 | "execution_count": null, 356 | "outputs": [ 357 | { 358 | "output_type": "stream", 359 | "text": [ 360 | "Orange\n", 361 | "Banana\n", 362 | "Cherry\n", 363 | "Orange\n", 364 | "Orange\n", 365 | "Orange\n" 366 | ], 367 | "name": "stdout" 368 | } 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "metadata": { 374 | "colab": { 375 | "base_uri": "https://localhost:8080/" 376 | }, 377 | "id": "ljbHKNSQzqut", 378 | "outputId": "9ab5269d-0a10-4dc2-d9cb-bf314aeb8f2a" 379 | }, 380 | "source": [ 381 | "# Unpack a Collection-- Tuple Unpacking\r\n", 382 | "\r\n", 383 | "fruits = [\"apple\", \"banana\", \"cherry\"]\r\n", 384 | "x, y, z = fruits\r\n", 385 | "print(x)\r\n", 386 | "print(y)\r\n", 387 | "print(z)" 388 | ], 389 | "execution_count": null, 390 | "outputs": [ 391 | { 392 | "output_type": "stream", 393 | "text": [ 394 | "apple\n", 395 | "banana\n", 396 | "cherry\n" 397 | ], 398 | "name": "stdout" 399 | } 400 | ] 401 | }, 402 | { 403 | "cell_type": "markdown", 404 | "metadata": { 405 | "id": "pdfA6KM15G3h" 406 | }, 407 | "source": [ 408 | "#### __d. Output Varibles__" 409 | ] 410 | }, 411 | { 412 | "cell_type": "code", 413 | "metadata": { 414 | "colab": { 415 | "base_uri": "https://localhost:8080/" 416 | }, 417 | "id": "RwUFWtWO02Yk", 418 | "outputId": "83deb526-e7fb-499a-e3aa-674f7f434771" 419 | }, 420 | "source": [ 421 | "# Output Variables\r\n", 422 | "\r\n", 423 | "a = \"awesome\"\r\n", 424 | "print(\"Python is \" + a)\r\n", 425 | "\r\n", 426 | "x = \"Python is \"\r\n", 427 | "y = \"awesome\"\r\n", 428 | "z = x + y\r\n", 429 | "print(z)\r\n", 430 | "\r\n", 431 | "p = 5\r\n", 432 | "q = 10\r\n", 433 | "print(p + q)" 434 | ], 435 | "execution_count": null, 436 | "outputs": [ 437 | { 438 | "output_type": "stream", 439 | "text": [ 440 | "Python is awesome\n", 441 | "Python is awesome\n", 442 | "15\n" 443 | ], 444 | "name": "stdout" 445 | } 446 | ] 447 | }, 448 | { 449 | "cell_type": "markdown", 450 | "metadata": { 451 | "id": "DZhOk4y81NVM" 452 | }, 453 | "source": [ 454 | "```python\r\n", 455 | "# Combine a string and a number\r\n", 456 | "# Python will give you an error\r\n", 457 | "\r\n", 458 | "Example\r\n", 459 | "x = 5\r\n", 460 | "y = \"John\"\r\n", 461 | "print(x + y)\r\n", 462 | "```" 463 | ] 464 | }, 465 | { 466 | "cell_type": "markdown", 467 | "metadata": { 468 | "id": "RtKLlkdI5W1s" 469 | }, 470 | "source": [ 471 | "#### __e. Global Variables__" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "metadata": { 477 | "colab": { 478 | "base_uri": "https://localhost:8080/" 479 | }, 480 | "id": "4vFacheI0npf", 481 | "outputId": "79e2b402-8ec1-4c1f-809a-63fd321c0832" 482 | }, 483 | "source": [ 484 | "# Global Variables\r\n", 485 | "# Create a variable outside of a function\r\n", 486 | "# and use it inside the function\r\n", 487 | "\r\n", 488 | "x = \"awesome\"\r\n", 489 | "\r\n", 490 | "def myfunc():\r\n", 491 | " print(\"Python is \" + x)\r\n", 492 | "\r\n", 493 | "myfunc()" 494 | ], 495 | "execution_count": null, 496 | "outputs": [ 497 | { 498 | "output_type": "stream", 499 | "text": [ 500 | "Python is awesome\n" 501 | ], 502 | "name": "stdout" 503 | } 504 | ] 505 | }, 506 | { 507 | "cell_type": "code", 508 | "metadata": { 509 | "colab": { 510 | "base_uri": "https://localhost:8080/" 511 | }, 512 | "id": "YbNN8Pqr1vrP", 513 | "outputId": "79ff9edb-05cb-4770-a802-a5aca6147503" 514 | }, 515 | "source": [ 516 | "# Create a variable inside a function\r\n", 517 | "# with the same name as the global variable\r\n", 518 | "\r\n", 519 | "x = \"awesome\"\r\n", 520 | "\r\n", 521 | "def myfunc():\r\n", 522 | " x = \"fantastic\"\r\n", 523 | " print(\"Python is \" + x)\r\n", 524 | "\r\n", 525 | "myfunc()\r\n", 526 | "\r\n", 527 | "print(\"Python is \" + x)" 528 | ], 529 | "execution_count": null, 530 | "outputs": [ 531 | { 532 | "output_type": "stream", 533 | "text": [ 534 | "Python is fantastic\n", 535 | "Python is awesome\n" 536 | ], 537 | "name": "stdout" 538 | } 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "metadata": { 544 | "colab": { 545 | "base_uri": "https://localhost:8080/" 546 | }, 547 | "id": "kGlxuKnt18N7", 548 | "outputId": "f769751e-fd85-4533-a2e1-045282988e7a" 549 | }, 550 | "source": [ 551 | "# The global Keyword\r\n", 552 | "\r\n", 553 | "# If you use the global keyword\r\n", 554 | "# the variable belongs to the global scope:\r\n", 555 | "\r\n", 556 | "def myfunc():\r\n", 557 | " global x\r\n", 558 | " x = \"fantastic\"\r\n", 559 | "\r\n", 560 | "myfunc()\r\n", 561 | "\r\n", 562 | "print(\"Python is \" + x)" 563 | ], 564 | "execution_count": null, 565 | "outputs": [ 566 | { 567 | "output_type": "stream", 568 | "text": [ 569 | "Python is fantastic\n" 570 | ], 571 | "name": "stdout" 572 | } 573 | ] 574 | }, 575 | { 576 | "cell_type": "code", 577 | "metadata": { 578 | "colab": { 579 | "base_uri": "https://localhost:8080/" 580 | }, 581 | "id": "_KZedbY53r4E", 582 | "outputId": "3f901ee4-14af-4534-f5f3-9bfe81265620" 583 | }, 584 | "source": [ 585 | "# To change the value of a global variable inside a function\r\n", 586 | "# refer to the variable by using the global keyword\r\n", 587 | "\r\n", 588 | "x = \"awesome\"\r\n", 589 | "\r\n", 590 | "def myfunc():\r\n", 591 | " global x\r\n", 592 | " x = \"fantastic\"\r\n", 593 | "\r\n", 594 | " myfunc()\r\n", 595 | "\r\n", 596 | "print(\"Python is \" + x)" 597 | ], 598 | "execution_count": null, 599 | "outputs": [ 600 | { 601 | "output_type": "stream", 602 | "text": [ 603 | "Python is fantastic\n" 604 | ], 605 | "name": "stdout" 606 | } 607 | ] 608 | } 609 | ] 610 | } -------------------------------------------------------------------------------- /02_Python_Foundations/06_Python_File_Handling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "06_Python_File_Handling.ipynb", 7 | "provenance": [], 8 | "authorship_tag": "ABX9TyMtopwr4hAPYcvMaydyOe1L", 9 | "include_colab_link": true 10 | }, 11 | "kernelspec": { 12 | "name": "python3", 13 | "display_name": "Python 3" 14 | } 15 | }, 16 | "cells": [ 17 | { 18 | "cell_type": "markdown", 19 | "metadata": { 20 | "id": "view-in-github", 21 | "colab_type": "text" 22 | }, 23 | "source": [ 24 | "\"Open" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": { 30 | "id": "-aRXV__RQ9aV" 31 | }, 32 | "source": [ 33 | "--- \r\n", 34 | " \r\n", 35 | "

File handling

\r\n", 36 | "
\r\n", 37 | "\r\n", 38 | "---" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": { 44 | "id": "nsLBd09XRICn" 45 | }, 46 | "source": [ 47 | "## __Python File Handling__" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "metadata": { 53 | "id": "0rdN3XbWR2j4" 54 | }, 55 | "source": [ 56 | "The `open()` function takes two parameters; __filename__, and __mode__.\r\n", 57 | "\r\n", 58 | "- `\"r\"` - Read - Default value. Opens a file for reading, error if the file does not exist\r\n", 59 | "\r\n", 60 | "- `\"a\"` - Append - Opens a file for appending, creates the file if it does not exist\r\n", 61 | "\r\n", 62 | "- `\"w\"` - Write - Opens a file for writing, creates the file if it does not exist\r\n", 63 | "\r\n", 64 | "- `\"x\"` - Create - Creates the specified file, returns an error if the file exists\r\n", 65 | "\r\n", 66 | "- `\"t\"` - Text - Default value. Text mode\r\n", 67 | "\r\n", 68 | "- `\"b\"` - Binary - Binary mode (e.g. images)" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "metadata": { 74 | "colab": { 75 | "base_uri": "https://localhost:8080/" 76 | }, 77 | "id": "hKU_9VR5YFsp", 78 | "outputId": "cea28422-5a40-418f-b549-cfdcb5a0623a" 79 | }, 80 | "source": [ 81 | "# writing my file\r\n", 82 | "\r\n", 83 | "%%writefile myfile.txt\r\n", 84 | "Democracy is not a state.\r\n", 85 | "It is an act, and each generation must do its part." 86 | ], 87 | "execution_count": 1, 88 | "outputs": [ 89 | { 90 | "output_type": "stream", 91 | "text": [ 92 | "Writing myfile.txt\n" 93 | ], 94 | "name": "stdout" 95 | } 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": { 101 | "id": "2ZxsEBnCRHtl" 102 | }, 103 | "source": [ 104 | "## __Python Read Files__" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "metadata": { 110 | "colab": { 111 | "base_uri": "https://localhost:8080/" 112 | }, 113 | "id": "uCSWAaUdRqw2", 114 | "outputId": "8be5826d-b341-4a9f-b2e6-3b128207c6c6" 115 | }, 116 | "source": [ 117 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 118 | "print(f.read())" 119 | ], 120 | "execution_count": 2, 121 | "outputs": [ 122 | { 123 | "output_type": "stream", 124 | "text": [ 125 | "Democracy is not a state.\n", 126 | "It is an act, and each generation must do its part.\n" 127 | ], 128 | "name": "stdout" 129 | } 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "metadata": { 135 | "colab": { 136 | "base_uri": "https://localhost:8080/" 137 | }, 138 | "id": "87tgK8yxWey8", 139 | "outputId": "7fe8afb5-97f0-4607-e0ba-256830f8bc09" 140 | }, 141 | "source": [ 142 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 143 | "print(f.read(10)) # Return the 10 first characters of the file:" 144 | ], 145 | "execution_count": 3, 146 | "outputs": [ 147 | { 148 | "output_type": "stream", 149 | "text": [ 150 | "Democracy \n" 151 | ], 152 | "name": "stdout" 153 | } 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "metadata": { 159 | "colab": { 160 | "base_uri": "https://localhost:8080/" 161 | }, 162 | "id": "btnECHPhW6RY", 163 | "outputId": "dcefe021-97a2-43fd-e8ca-9255e13c6138" 164 | }, 165 | "source": [ 166 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 167 | "print(f.readline()) # Read one line of the file" 168 | ], 169 | "execution_count": 4, 170 | "outputs": [ 171 | { 172 | "output_type": "stream", 173 | "text": [ 174 | "Democracy is not a state.\n", 175 | "\n" 176 | ], 177 | "name": "stdout" 178 | } 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "metadata": { 184 | "colab": { 185 | "base_uri": "https://localhost:8080/" 186 | }, 187 | "id": "HyotnzGEYWTO", 188 | "outputId": "81f2daf3-6d2b-46fb-ea20-d1b6417dd07a" 189 | }, 190 | "source": [ 191 | "# By looping through the lines of the file\r\n", 192 | "# we can read the whole file, line by line\r\n", 193 | "\r\n", 194 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 195 | "for x in f:\r\n", 196 | " print(x)" 197 | ], 198 | "execution_count": 5, 199 | "outputs": [ 200 | { 201 | "output_type": "stream", 202 | "text": [ 203 | "Democracy is not a state.\n", 204 | "\n", 205 | "It is an act, and each generation must do its part.\n" 206 | ], 207 | "name": "stdout" 208 | } 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "metadata": { 214 | "colab": { 215 | "base_uri": "https://localhost:8080/" 216 | }, 217 | "id": "TIqmhH7jYlUT", 218 | "outputId": "b5bf8e8b-9a7d-4922-9d65-5faf927e4a0e" 219 | }, 220 | "source": [ 221 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 222 | "print(f.readline())\r\n", 223 | "f.close()" 224 | ], 225 | "execution_count": 6, 226 | "outputs": [ 227 | { 228 | "output_type": "stream", 229 | "text": [ 230 | "Democracy is not a state.\n", 231 | "\n" 232 | ], 233 | "name": "stdout" 234 | } 235 | ] 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "metadata": { 240 | "id": "kAhzx0H2RHhW" 241 | }, 242 | "source": [ 243 | "## __Python Write/Create Files__" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "metadata": { 249 | "colab": { 250 | "base_uri": "https://localhost:8080/" 251 | }, 252 | "id": "WhRWBkr2Rrj1", 253 | "outputId": "a5da45fe-bcea-4714-f455-3c09022c2c24" 254 | }, 255 | "source": [ 256 | "f = open(\"/content/myfile.txt\", \"a\")\r\n", 257 | "f.write(\"\\nNow the file has more content!\")\r\n", 258 | "f.close()\r\n", 259 | "\r\n", 260 | "#open and read the file after the appending:\r\n", 261 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 262 | "print(f.read())" 263 | ], 264 | "execution_count": 7, 265 | "outputs": [ 266 | { 267 | "output_type": "stream", 268 | "text": [ 269 | "Democracy is not a state.\n", 270 | "It is an act, and each generation must do its part.\n", 271 | "Now the file has more content!\n" 272 | ], 273 | "name": "stdout" 274 | } 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "metadata": { 280 | "colab": { 281 | "base_uri": "https://localhost:8080/" 282 | }, 283 | "id": "8BF6P3viRsLp", 284 | "outputId": "c4d11e83-5eaf-42e7-c3c2-c28ca1deeb2b" 285 | }, 286 | "source": [ 287 | "f = open(\"/content/myfile.txt\", \"w\")\r\n", 288 | "f.write(\"Woops! I have deleted the content!\")\r\n", 289 | "f.close()\r\n", 290 | "\r\n", 291 | "#open and read the file after the appending:\r\n", 292 | "f = open(\"/content/myfile.txt\", \"r\")\r\n", 293 | "print(f.read())" 294 | ], 295 | "execution_count": 8, 296 | "outputs": [ 297 | { 298 | "output_type": "stream", 299 | "text": [ 300 | "Woops! I have deleted the content!\n" 301 | ], 302 | "name": "stdout" 303 | } 304 | ] 305 | }, 306 | { 307 | "cell_type": "markdown", 308 | "metadata": { 309 | "id": "KmQChjSNal3r" 310 | }, 311 | "source": [ 312 | "__Creating a new file if it does not exist__" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "metadata": { 318 | "id": "qvzzuODqaTvR" 319 | }, 320 | "source": [ 321 | "f = open(\"NewFile.txt\", \"w\")" 322 | ], 323 | "execution_count": 9, 324 | "outputs": [] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "metadata": { 329 | "id": "R-N_VhXERhUb" 330 | }, 331 | "source": [ 332 | "## __Pyhton Delete Files__" 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "metadata": { 338 | "id": "z7IgabmwaDwy" 339 | }, 340 | "source": [ 341 | "import os\r\n", 342 | "if os.path.exists(\"/content\"):\r\n", 343 | " os.remove(\"NewFile.txt\")\r\n", 344 | "else:\r\n", 345 | " print(\"The file does not exist\")" 346 | ], 347 | "execution_count": 10, 348 | "outputs": [] 349 | }, 350 | { 351 | "cell_type": "markdown", 352 | "metadata": { 353 | "id": "tnVOwkhNbqt6" 354 | }, 355 | "source": [ 356 | "```python \r\n", 357 | "# Remove the folder \"myfolder\"\r\n", 358 | "\r\n", 359 | "import os\r\n", 360 | "os.rmdir(\"myfolder\")\r\n", 361 | "```" 362 | ] 363 | } 364 | ] 365 | } -------------------------------------------------------------------------------- /03_Python_Object_Oriented_Programming/module.py: -------------------------------------------------------------------------------- 1 | def add(a, b): 2 | return a + b 3 | 4 | def subtract(a, b): 5 | return a - b 6 | 7 | def multiply(a, b): 8 | return a * b 9 | 10 | def divide(a, b): 11 | return a / b 12 | 13 | print("I'm being run directly", __name__) 14 | 15 | if __name__ == '__main__': 16 | print(add(4, 3)) 17 | print(subtract(4, 3)) 18 | print(multiply(4, 3)) 19 | print(divide(8, 4)) 20 | -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/01_Dice_Simulater.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "01_Dice_Simulater.ipynb", 7 | "provenance": [], 8 | "toc_visible": true, 9 | "authorship_tag": "ABX9TyNZcLwbtTy08QK5CHrMi4WV", 10 | "include_colab_link": true 11 | }, 12 | "kernelspec": { 13 | "name": "python3", 14 | "display_name": "Python 3" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "id": "view-in-github", 22 | "colab_type": "text" 23 | }, 24 | "source": [ 25 | "\"Open" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": { 31 | "id": "sE1CDvR6olkz" 32 | }, 33 | "source": [ 34 | "--- \r\n", 35 | " \r\n", 36 | "

Dice Rolling Simulator

\r\n", 37 | "
\r\n", 38 | "\r\n", 39 | "---\r\n", 40 | "\r\n", 41 | "\r\n", 42 | "

\r\n", 43 | " \r\n", 44 | " \"\"\r\n", 45 | " \r\n", 46 | "

" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "metadata": { 52 | "colab": { 53 | "base_uri": "https://localhost:8080/" 54 | }, 55 | "id": "iV3G_Na0gee4", 56 | "outputId": "bc4895e2-bf87-43cc-8753-ed99336d9a4c" 57 | }, 58 | "source": [ 59 | "# dice Simulater\r\n", 60 | "'''\r\n", 61 | "Think:\r\n", 62 | "1. dice UI\r\n", 63 | "2. random face number\r\n", 64 | "3. Looping\r\n", 65 | "\r\n", 66 | "Algorithm:\r\n", 67 | "1. generating the random numbeer\r\n", 68 | "2. check the number\r\n", 69 | "3. print the face\r\n", 70 | "4. looping\r\n", 71 | "'''\r\n", 72 | "import random\r\n", 73 | "\r\n", 74 | "x = 'y'\r\n", 75 | "\r\n", 76 | "while x == \"y\":\r\n", 77 | " number = random.randint(1, 6)\r\n", 78 | "\r\n", 79 | " if number == 1:\r\n", 80 | " print('-----------')\r\n", 81 | " print('| |')\r\n", 82 | " print('| 0 |')\r\n", 83 | " print('| |')\r\n", 84 | " print('-----------')\r\n", 85 | "\r\n", 86 | " if number == 2:\r\n", 87 | " print('-----------')\r\n", 88 | " print('| |')\r\n", 89 | " print('|0 0|')\r\n", 90 | " print('| |')\r\n", 91 | " print('-----------')\r\n", 92 | "\r\n", 93 | " if number == 3:\r\n", 94 | " print('-----------')\r\n", 95 | " print('| 0|')\r\n", 96 | " print('| 0 |')\r\n", 97 | " print('|0 |')\r\n", 98 | " print('-----------')\r\n", 99 | "\r\n", 100 | " if number == 4:\r\n", 101 | " print('-----------')\r\n", 102 | " print('|0 0|')\r\n", 103 | " print('| |')\r\n", 104 | " print('|0 0|')\r\n", 105 | " print('-----------')\r\n", 106 | "\r\n", 107 | " if number == 5:\r\n", 108 | " print('-----------')\r\n", 109 | " print('|0 0|')\r\n", 110 | " print('| 0 |')\r\n", 111 | " print('|0 0|')\r\n", 112 | " print('-----------')\r\n", 113 | "\r\n", 114 | " if number == 6:\r\n", 115 | " print('--------- -')\r\n", 116 | " print('|0 0|')\r\n", 117 | " print('|0 0|')\r\n", 118 | " print('|0 0|')\r\n", 119 | " print('-----------')\r\n", 120 | "\r\n", 121 | " x = input(\"Press y to roll again \")\r\n" 122 | ], 123 | "execution_count": null, 124 | "outputs": [ 125 | { 126 | "output_type": "stream", 127 | "text": [ 128 | "-----------\n", 129 | "|0 0|\n", 130 | "| 0 |\n", 131 | "|0 0|\n", 132 | "-----------\n", 133 | "Press y to roll again y\n", 134 | "-----------\n", 135 | "|0 0|\n", 136 | "| |\n", 137 | "|0 0|\n", 138 | "-----------\n", 139 | "Press y to roll again y\n", 140 | "-----------\n", 141 | "|0 0|\n", 142 | "| |\n", 143 | "|0 0|\n", 144 | "-----------\n", 145 | "Press y to roll again y\n", 146 | "-----------\n", 147 | "| |\n", 148 | "| 0 |\n", 149 | "| |\n", 150 | "-----------\n", 151 | "Press y to roll again y\n", 152 | "--------- -\n", 153 | "|0 0|\n", 154 | "|0 0|\n", 155 | "|0 0|\n", 156 | "-----------\n", 157 | "Press y to roll again y\n", 158 | "-----------\n", 159 | "| |\n", 160 | "| 0 |\n", 161 | "| |\n", 162 | "-----------\n", 163 | "Press y to roll again y\n", 164 | "-----------\n", 165 | "| |\n", 166 | "|0 0|\n", 167 | "| |\n", 168 | "-----------\n", 169 | "Press y to roll again y\n", 170 | "--------- -\n", 171 | "|0 0|\n", 172 | "|0 0|\n", 173 | "|0 0|\n", 174 | "-----------\n", 175 | "Press y to roll again \n" 176 | ], 177 | "name": "stdout" 178 | } 179 | ] 180 | } 181 | ] 182 | } -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/04_ProjPy_Tic-Tac-Toe_Game.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Z01_PYTHON_PROJECT_01.ipynb", 7 | "provenance": [], 8 | "toc_visible": true, 9 | "authorship_tag": "ABX9TyNXC3mjnYUzskYUMXV72J4q", 10 | "include_colab_link": true 11 | }, 12 | "kernelspec": { 13 | "name": "python3", 14 | "display_name": "Python 3" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "id": "view-in-github", 22 | "colab_type": "text" 23 | }, 24 | "source": [ 25 | "\"Open" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": { 31 | "id": "55jmoEnRC2r8", 32 | "colab_type": "text" 33 | }, 34 | "source": [ 35 | "# __TIC TAC TOE IN PYTHON__" 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": { 41 | "id": "wVWukxZ0CzWR", 42 | "colab_type": "text" 43 | }, 44 | "source": [ 45 | "1. **Printing a Board**\n", 46 | "2. **Player input.**\n", 47 | "3. **('X' or 'O') Place marker**\n", 48 | "4. **Win Checker**\n", 49 | "5. **Randomly decide which player goes first**\n", 50 | "6. **whether a space on the board is freely available**\n", 51 | "7. **If the board is full and returns a boolean value**\n", 52 | "8. **Asks for a player's next position (as a number 1-9) & Then uses the function from step 6 to check if its a free position**\n", 53 | "9. **If the Player wants to play again**\n", 54 | "10. __MAIN LOGIC__" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": { 60 | "id": "zj1uMclTkDLE", 61 | "colab_type": "text" 62 | }, 63 | "source": [ 64 | "# __1. Display board__" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "metadata": { 70 | "id": "rP6hrPBHRx6R", 71 | "colab_type": "code", 72 | "colab": { 73 | "base_uri": "https://localhost:8080/", 74 | "height": 105 75 | }, 76 | "outputId": "1c175202-971b-495f-9db3-f741665e76fc" 77 | }, 78 | "source": [ 79 | "from IPython.display import clear_output\n", 80 | " \n", 81 | "def display_board(board):\n", 82 | " clear_output()\n", 83 | "\n", 84 | " print(' ' + board[7] + ' | '+ board[8]+ ' | ' +board[9])\n", 85 | " print('---+---+---')\n", 86 | " print(' ' + board[4] + ' | '+ board[5]+ ' | ' +board[6])\n", 87 | " print('---+---+---')\n", 88 | " print(' ' + board[1] + ' | '+ board[2]+ ' | ' +board[3]) \n", 89 | "\n", 90 | "\n", 91 | "test_board = ['#','X','O','X','O','X','O','X','O','X']\n", 92 | "display_board(test_board)" 93 | ], 94 | "execution_count": 1, 95 | "outputs": [ 96 | { 97 | "output_type": "stream", 98 | "text": [ 99 | " X | O | X\n", 100 | "---+---+---\n", 101 | " O | X | O\n", 102 | "---+---+---\n", 103 | " X | O | X\n" 104 | ], 105 | "name": "stdout" 106 | } 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": { 112 | "id": "YrOu07pPkl1N", 113 | "colab_type": "text" 114 | }, 115 | "source": [ 116 | "# __2. Choose the Marker ('X' or 'O')__" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "metadata": { 122 | "id": "eLqETmptklaJ", 123 | "colab_type": "code", 124 | "colab": { 125 | "base_uri": "https://localhost:8080/", 126 | "height": 72 127 | }, 128 | "outputId": "51111e48-49c4-4220-80cf-ae3d75ecf489" 129 | }, 130 | "source": [ 131 | "def player_input():\n", 132 | " \n", 133 | " '''\n", 134 | " OUTPUT: Player 1 marker, Player 2 marker\n", 135 | " '''\n", 136 | "\n", 137 | " marker = ''\n", 138 | "\n", 139 | " while not (marker == 'X' or marker == 'O'):\n", 140 | " marker= input('Choose: Do you want X or O? ').upper()\n", 141 | "\n", 142 | " if marker == 'X':\n", 143 | " return ('X', 'O') # Tuple Unpacking\n", 144 | " \n", 145 | " else: \n", 146 | " return('X','O') # Tuple Unpacking\n", 147 | "\n", 148 | "player_input()" 149 | ], 150 | "execution_count": 2, 151 | "outputs": [ 152 | { 153 | "output_type": "stream", 154 | "text": [ 155 | "Choose: Do you want X or O? X\n" 156 | ], 157 | "name": "stdout" 158 | }, 159 | { 160 | "output_type": "execute_result", 161 | "data": { 162 | "text/plain": [ 163 | "('X', 'O')" 164 | ] 165 | }, 166 | "metadata": { 167 | "tags": [] 168 | }, 169 | "execution_count": 2 170 | } 171 | ] 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "metadata": { 176 | "id": "owk7BmoIsq5a", 177 | "colab_type": "text" 178 | }, 179 | "source": [ 180 | "# __3. Place Marker ('X' or 'O')__" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "metadata": { 186 | "id": "iAWfLLmwsR0M", 187 | "colab_type": "code", 188 | "colab": { 189 | "base_uri": "https://localhost:8080/", 190 | "height": 105 191 | }, 192 | "outputId": "3df41b3c-9d0a-41bb-da3e-9745c86fb091" 193 | }, 194 | "source": [ 195 | "def place_marker(board, marker, position):\n", 196 | " board[position] = marker\n", 197 | "\n", 198 | "place_marker(test_board,'$',8)\n", 199 | "display_board(test_board)\n", 200 | " " 201 | ], 202 | "execution_count": 3, 203 | "outputs": [ 204 | { 205 | "output_type": "stream", 206 | "text": [ 207 | " X | $ | X\n", 208 | "---+---+---\n", 209 | " O | X | O\n", 210 | "---+---+---\n", 211 | " X | O | X\n" 212 | ], 213 | "name": "stdout" 214 | } 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": { 220 | "id": "YVxjgn2l9640", 221 | "colab_type": "text" 222 | }, 223 | "source": [ 224 | "# __4. WIN Check__" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "metadata": { 230 | "id": "KElZK2ev-GPU", 231 | "colab_type": "code", 232 | "colab": { 233 | "base_uri": "https://localhost:8080/", 234 | "height": 34 235 | }, 236 | "outputId": "1f9cb09b-b834-4aef-abdf-262ff0a856c0" 237 | }, 238 | "source": [ 239 | " \n", 240 | "def win_check(board,mark):\n", 241 | " \n", 242 | " return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top\n", 243 | " (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle\n", 244 | " (board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom\n", 245 | " (board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle\n", 246 | " (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle\n", 247 | " (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side\n", 248 | " (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal\n", 249 | " (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal\n", 250 | " \n", 251 | "win_check(test_board,'X')" 252 | ], 253 | "execution_count": 4, 254 | "outputs": [ 255 | { 256 | "output_type": "execute_result", 257 | "data": { 258 | "text/plain": [ 259 | "True" 260 | ] 261 | }, 262 | "metadata": { 263 | "tags": [] 264 | }, 265 | "execution_count": 4 266 | } 267 | ] 268 | }, 269 | { 270 | "cell_type": "markdown", 271 | "metadata": { 272 | "id": "BWOGxsGZwz1f", 273 | "colab_type": "text" 274 | }, 275 | "source": [ 276 | "# __5. Randomly Decide which palayer goes first__" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "metadata": { 282 | "id": "-KV7GFixUA9e", 283 | "colab_type": "code", 284 | "colab": {} 285 | }, 286 | "source": [ 287 | "import random\n", 288 | "\n", 289 | "def choose_first():\n", 290 | "\n", 291 | " if random.randint(0,1) == 0:\n", 292 | " return 'Player 2'\n", 293 | " else:\n", 294 | " return 'Player 1'" 295 | ], 296 | "execution_count": 5, 297 | "outputs": [] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": { 302 | "id": "q6Dd8UFpx303", 303 | "colab_type": "text" 304 | }, 305 | "source": [ 306 | "# __6. Space Check__" 307 | ] 308 | }, 309 | { 310 | "cell_type": "markdown", 311 | "metadata": { 312 | "id": "56JgcrXqz479", 313 | "colab_type": "text" 314 | }, 315 | "source": [ 316 | "*Wether the board is freely avalible*\n", 317 | "\n", 318 | " if it returns **False** $\\Rightarrow $ *Space is not avalible*" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "metadata": { 324 | "id": "PDTEDvhmz36f", 325 | "colab_type": "code", 326 | "colab": {} 327 | }, 328 | "source": [ 329 | "def space_check(board, position):\n", 330 | "\n", 331 | " return board[position] == ' ' " 332 | ], 333 | "execution_count": 6, 334 | "outputs": [] 335 | }, 336 | { 337 | "cell_type": "markdown", 338 | "metadata": { 339 | "id": "27rZaAR8525o", 340 | "colab_type": "text" 341 | }, 342 | "source": [ 343 | "# __7. Full Board Check__" 344 | ] 345 | }, 346 | { 347 | "cell_type": "markdown", 348 | "metadata": { 349 | "id": "5UaIijub6GJq", 350 | "colab_type": "text" 351 | }, 352 | "source": [ 353 | "*If the board is full and returns a boolean value*" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "metadata": { 359 | "id": "fApCAyZL5meP", 360 | "colab_type": "code", 361 | "colab": {} 362 | }, 363 | "source": [ 364 | "def full_board_check(board):\n", 365 | "\n", 366 | " for i in range(1,10):\n", 367 | " if space_check(board, i):\n", 368 | " return False\n", 369 | " \n", 370 | " return True" 371 | ], 372 | "execution_count": 7, 373 | "outputs": [] 374 | }, 375 | { 376 | "cell_type": "markdown", 377 | "metadata": { 378 | "id": "P-CQ8GqxHU2b", 379 | "colab_type": "text" 380 | }, 381 | "source": [ 382 | "# __8. Player Choice__\n" 383 | ] 384 | }, 385 | { 386 | "cell_type": "markdown", 387 | "metadata": { 388 | "id": "GrIuquwAHKQo", 389 | "colab_type": "text" 390 | }, 391 | "source": [ 392 | "- *Asks for a player's next position (as a number 1-9)*\n", 393 | "- *Then uses the function from step 6 to check if its a free position*\n", 394 | " " 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "metadata": { 400 | "id": "vhI5EQZq7Rq0", 401 | "colab_type": "code", 402 | "colab": {} 403 | }, 404 | "source": [ 405 | "def player_choice(board):\n", 406 | " position = 0\n", 407 | " \n", 408 | " while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):\n", 409 | " position = int(input('Choose your next position: (1-9) '))\n", 410 | " \n", 411 | " return position" 412 | ], 413 | "execution_count": 8, 414 | "outputs": [] 415 | }, 416 | { 417 | "cell_type": "markdown", 418 | "metadata": { 419 | "id": "Eand6uNBPFUk", 420 | "colab_type": "text" 421 | }, 422 | "source": [ 423 | "# __9. Replay__\n" 424 | ] 425 | }, 426 | { 427 | "cell_type": "markdown", 428 | "metadata": { 429 | "id": "T4A6rnoXPR51", 430 | "colab_type": "text" 431 | }, 432 | "source": [ 433 | "*if the palyer want to play again.*" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "metadata": { 439 | "id": "ti2S7XrBOtvK", 440 | "colab_type": "code", 441 | "colab": {} 442 | }, 443 | "source": [ 444 | "def replay():\n", 445 | " \n", 446 | " return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')" 447 | ], 448 | "execution_count": 9, 449 | "outputs": [] 450 | }, 451 | { 452 | "cell_type": "markdown", 453 | "metadata": { 454 | "id": "G-xwEt5iRm2Y", 455 | "colab_type": "text" 456 | }, 457 | "source": [ 458 | "# __10. Main Logic__" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "metadata": { 464 | "id": "cVLBTNT8ui_h", 465 | "colab_type": "code", 466 | "colab": { 467 | "base_uri": "https://localhost:8080/", 468 | "height": 161 469 | }, 470 | "outputId": "ee5db3d7-f645-45c2-aedb-01b93d3b5b6a" 471 | }, 472 | "source": [ 473 | "# While loop to keep palying the GAME\n", 474 | "print('Welcome to Tic Tac Toe!')\n", 475 | " \n", 476 | "while True:\n", 477 | " # Play the GAME\n", 478 | " ## Set Everything UP (Board. Whos First, Choose Marker X,O)\n", 479 | " \n", 480 | " the_board = [' '] * 10 # 1\n", 481 | " player1_marker, player2_marker = player_input() # 2 \n", 482 | " turn = choose_first() # 5\n", 483 | " print(turn + ' will go first.')\n", 484 | " \n", 485 | " play_game = input('Are you ready to play? Enter Yes or No: ')\n", 486 | " \n", 487 | " if play_game.lower()[0] == 'y':\n", 488 | " game_on = True\n", 489 | " else:\n", 490 | " game_on = False\n", 491 | " \n", 492 | " while game_on:\n", 493 | "\n", 494 | " if turn == 'Player 1':\n", 495 | "\n", 496 | " # ----------Player1's turn----------\n", 497 | " \n", 498 | " # Show the Board \n", 499 | " display_board(the_board)\n", 500 | " # Choose the Position # 1\n", 501 | " position = player_choice(the_board)\n", 502 | " # Place the marker on the position # 8\n", 503 | " place_marker(the_board, player1_marker, position) # 3\n", 504 | " # Check if they WON\n", 505 | " if win_check(the_board, player1_marker): # 4\n", 506 | " display_board(the_board) # 1\n", 507 | " print('Congratulations! You have won the game!')\n", 508 | " game_on = False\n", 509 | " else:\n", 510 | " # Or Check if there is a tie\n", 511 | " if full_board_check(the_board):\n", 512 | " display_board(the_board)\n", 513 | " print('The game is a draw!')\n", 514 | " break\n", 515 | " else:\n", 516 | " # No Tie/No Win, Then its nest player turn\n", 517 | " turn = 'Player 2'\n", 518 | " \n", 519 | " else:\n", 520 | " # ----------Player2's turn----------\n", 521 | " \n", 522 | " display_board(the_board)\n", 523 | " position = player_choice(the_board)\n", 524 | " place_marker(the_board, player2_marker, position)\n", 525 | " \n", 526 | " if win_check(the_board, player2_marker):\n", 527 | " display_board(the_board)\n", 528 | " print('Player 2 has won!')\n", 529 | " game_on = False\n", 530 | " else:\n", 531 | " if full_board_check(the_board):\n", 532 | " display_board(the_board)\n", 533 | " print('The game is a draw!')\n", 534 | " break\n", 535 | " else:\n", 536 | " turn = 'Player 1'\n", 537 | " \n", 538 | " if not replay(): # 9 \n", 539 | " break" 540 | ], 541 | "execution_count": 10, 542 | "outputs": [ 543 | { 544 | "output_type": "stream", 545 | "text": [ 546 | " O | | \n", 547 | "---+---+---\n", 548 | " X | O | X\n", 549 | "---+---+---\n", 550 | " O | X | O\n", 551 | "Player 2 has won!\n", 552 | "Do you want to play again? Enter Yes or No: n\n" 553 | ], 554 | "name": "stdout" 555 | } 556 | ] 557 | } 558 | ] 559 | } -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/05_Railway_Ticketing_Sys.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "collapsed_sections": [], 8 | "toc_visible": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "#
🚂Railway Ticketing System🚂
" 23 | ], 24 | "metadata": { 25 | "id": "8GtEPn2Oo3aU" 26 | } 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "source": [ 31 | "

\n", 32 | " \n", 33 | " \n", 34 | " \n", 35 | "

" 36 | ], 37 | "metadata": { 38 | "id": "_sHKOqaBplpF" 39 | } 40 | }, 41 | { 42 | "cell_type": "code", 43 | "source": [ 44 | "class Train:\n", 45 | " def __init__(self, name, seats):\n", 46 | " self.name = name\n", 47 | " self.seats = seats\n", 48 | "\n", 49 | " def getStatus(self):\n", 50 | " if self.seats > 0 and self.seats < 73:\n", 51 | " print(\"--------------------------------------------------\")\n", 52 | " print(f\"Seats available : {self.seats}\")\n", 53 | " print(\"--------------------------------------------------\")\n", 54 | " else:\n", 55 | " print(\"No! seats are avalible\")\n", 56 | "\n", 57 | " def bookTicket(self):\n", 58 | " if self.seats > 0 and self.seats < 73:\n", 59 | " print(\"--------------------------------------------------\")\n", 60 | " print(f\"Your ticket has been booked!\")\n", 61 | " print(\"--------------------------------------------------\")\n", 62 | " print(f\"Train name: {self.name}\")\n", 63 | " self.seats = self.seats - 1\n", 64 | " else:\n", 65 | " print(\"Sorry this train is full! Kindly try in tatkal\")\n", 66 | "\n", 67 | " @staticmethod\n", 68 | " def fareInfo(s):\n", 69 | " if s > 0 and s < 73:\n", 70 | " if s % 8 == 1 or s % 8 == 4:\n", 71 | " return \"Rs 100\"\n", 72 | " elif s % 8 == 2 or s % 8 == 5:\n", 73 | " return \"Rs 90\"\n", 74 | " elif s % 8 == 3 or s % 8 == 6:\n", 75 | " return \"Rs 80\"\n", 76 | " elif s % 8 == 7:\n", 77 | " return \"Rs 120\"\n", 78 | " else:\n", 79 | " return \"Rs 140\"\n", 80 | " else:\n", 81 | " return \"Error :( Try again\"\n", 82 | " \n", 83 | " @staticmethod\n", 84 | " def berth_type(s):\n", 85 | " if s > 0 and s < 73:\n", 86 | " if s % 8 == 1 or s % 8 == 4:\n", 87 | " return \"Lower Berth\"\n", 88 | " elif s % 8 == 2 or s % 8 == 5:\n", 89 | " return \"Middle Berth\"\n", 90 | " elif s % 8 == 3 or s % 8 == 6:\n", 91 | " return \"Upper Berth\"\n", 92 | " elif s % 8 == 7:\n", 93 | " return \"Side Lower Berth\"\n", 94 | " else:\n", 95 | " return \"Side Upper Berth\"\n", 96 | " else:\n", 97 | " return \"Invalid seat Number\"\n", 98 | " \n", 99 | " def cancleTicket(self):\n", 100 | " if self.seats > 0 and self.seats < 73:\n", 101 | " print(f\"Your ticket has been cancelled! Your seat number is {self.seats+1}\")\n", 102 | " self.seats = self.seats + 1\n", 103 | " else:\n", 104 | " print(\"No ticket to cancel\")\n", 105 | "\n", 106 | "\n", 107 | "s = int(input(\"Enter the seat number: \")) \n", 108 | "# Creating the object of a class\n", 109 | "intercity = Train(\"Intercity Express: 12036\", s)\n", 110 | "\n", 111 | "intercity.bookTicket() # Booking the ticket\n", 112 | "print(f\"Seat number: {s}\")\n", 113 | "print(f\"seat location: {intercity.berth_type(s)}\") \n", 114 | "print(f\"Seat fare: {intercity.fareInfo(s)}\")\n", 115 | "intercity.getStatus() # Status after booking \n", 116 | "intercity.cancleTicket() # ticket Cancellation \n", 117 | "intercity.getStatus() # Status after Cancellation" 118 | ], 119 | "metadata": { 120 | "colab": { 121 | "base_uri": "https://localhost:8080/" 122 | }, 123 | "id": "FsC_Kei8VWhu", 124 | "outputId": "2c9bd6fb-16d2-4dfb-cc9f-235d743130c4" 125 | }, 126 | "execution_count": 52, 127 | "outputs": [ 128 | { 129 | "output_type": "stream", 130 | "name": "stdout", 131 | "text": [ 132 | "Enter the seat number: 2\n", 133 | "--------------------------------------------------\n", 134 | "Your ticket has been booked!\n", 135 | "--------------------------------------------------\n", 136 | "Train name: Intercity Express: 12036\n", 137 | "Seat number: 2\n", 138 | "seat location: Middle Berth\n", 139 | "Seat fare: Rs 90\n", 140 | "--------------------------------------------------\n", 141 | "Seats available : 1\n", 142 | "--------------------------------------------------\n", 143 | "Your ticket has been cancelled! Your seat number is 2\n", 144 | "--------------------------------------------------\n", 145 | "Seats available : 2\n", 146 | "--------------------------------------------------\n" 147 | ] 148 | } 149 | ] 150 | } 151 | ] 152 | } -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/06_Rock_Paper_Scissor.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "collapsed_sections": [], 8 | "toc_visible": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "#
Rock⛰Paper📃Scissors✂️
" 23 | ], 24 | "metadata": { 25 | "id": "EM35IK9X9Z-t" 26 | } 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "source": [ 31 | "

\n", 32 | " \n", 33 | " \"\"\n", 34 | " \n", 35 | "

" 36 | ], 37 | "metadata": { 38 | "id": "qcLnwUHKliv1" 39 | } 40 | }, 41 | { 42 | "cell_type": "code", 43 | "source": [ 44 | "import random\n", 45 | "\n", 46 | "# Rock Paper Scissors\n", 47 | "def gameWin(comp, you):\n", 48 | " # If two values are equal, declare a tie!\n", 49 | " if comp == you:\n", 50 | " return None\n", 51 | "\n", 52 | " # Check for all possibilities when computer chose rock\n", 53 | " elif comp == 'r':\n", 54 | " if you == 'p':\n", 55 | " return True\n", 56 | " elif you == 's':\n", 57 | " return False\n", 58 | " \n", 59 | " # Check for all possibilities when computer chose paper\n", 60 | " elif comp == 'p':\n", 61 | " if you == 's':\n", 62 | " return True\n", 63 | " elif you == 'r':\n", 64 | " return False\n", 65 | " \n", 66 | " # Check for all possibilities when computer chose scissors\n", 67 | " elif comp == 's':\n", 68 | " if you == 'r':\n", 69 | " return True\n", 70 | " elif you == 'p':\n", 71 | " return False\n", 72 | "\n", 73 | "print(\"Comp Turn: Rock(r) Paper(p) or Scissors(s)?\")\n", 74 | "randNo = random.randint(1, 3) \n", 75 | "if randNo == 1:\n", 76 | " comp = 'r'\n", 77 | "elif randNo == 2:\n", 78 | " comp = 'p'\n", 79 | "elif randNo == 3:\n", 80 | " comp = 's'\n", 81 | "\n", 82 | "you = input(\"Your Turn: Rock(r) Paper(p) or Scissors(s)?\")\n", 83 | "a = gameWin(comp, you)\n", 84 | "\n", 85 | "print(f\"Computer chose {comp}\")\n", 86 | "print(f\"You chose {you}\")\n", 87 | "\n", 88 | "if a == None:\n", 89 | " print(\"The game is a tie!\")\n", 90 | "elif a:\n", 91 | " print(\"You Win!\")\n", 92 | "else:\n", 93 | " print(\"You Lose!\")" 94 | ], 95 | "metadata": { 96 | "colab": { 97 | "base_uri": "https://localhost:8080/" 98 | }, 99 | "id": "tEoeJCUBhOBP", 100 | "outputId": "e6d79802-5922-4d4b-ec15-8d5966fee041" 101 | }, 102 | "execution_count": 1, 103 | "outputs": [ 104 | { 105 | "output_type": "stream", 106 | "name": "stdout", 107 | "text": [ 108 | "Comp Turn: Rock(r) Paper(p) or Scissors(s)?\n", 109 | "Your Turn: Rock(r) Paper(p) or Scissors(s)?r\n", 110 | "Computer chose p\n", 111 | "You chose r\n", 112 | "You Lose!\n" 113 | ] 114 | } 115 | ] 116 | } 117 | ] 118 | } -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/07_The_perfect_Guess.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "collapsed_sections": [], 8 | "toc_visible": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "#
⌛️The perfect Guess⏳
" 23 | ], 24 | "metadata": { 25 | "id": "8zYWN5IZWwLc" 26 | } 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "source": [ 31 | "📢**Write a program that genrates a random number and ask user to guess it.**\n", 32 | "\n", 33 | "- ✔️If the player guess is higher than the actual number, the program displays `\"Lower number please\"`. \n", 34 | "- ✔️Similarly if the user guess is too low, the program prints `\"higher number please\"`.\n", 35 | "- ✔️when the user guess the correct number, 👉**the program displays the number of guess.**" 36 | ], 37 | "metadata": { 38 | "id": "ihRDfHQgXF2-" 39 | } 40 | }, 41 | { 42 | "cell_type": "code", 43 | "source": [ 44 | "! pwd" 45 | ], 46 | "metadata": { 47 | "colab": { 48 | "base_uri": "https://localhost:8080/" 49 | }, 50 | "id": "BxJJDP-DfrVH", 51 | "outputId": "7eff4a16-41d5-42a5-9e5c-c09b5a5dcd34" 52 | }, 53 | "execution_count": null, 54 | "outputs": [ 55 | { 56 | "output_type": "stream", 57 | "name": "stdout", 58 | "text": [ 59 | "/content\n" 60 | ] 61 | } 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "source": [ 67 | "# This creates empty file name hiscore.txt\n", 68 | "! touch hiscore.txt" 69 | ], 70 | "metadata": { 71 | "id": "Qp9cfplkfmtS" 72 | }, 73 | "execution_count": null, 74 | "outputs": [] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "source": [ 79 | "guessHiScore = 9 # setting the high score to 9\n", 80 | "\n", 81 | "with open(\"/content/hiscore.txt\", \"w\") as f:\n", 82 | " f.write('%d' %guessHiScore)" 83 | ], 84 | "metadata": { 85 | "id": "gzMqVFBdkeXJ" 86 | }, 87 | "execution_count": null, 88 | "outputs": [] 89 | }, 90 | { 91 | "cell_type": "markdown", 92 | "source": [ 93 | "Play ▶▶" 94 | ], 95 | "metadata": { 96 | "id": "zQGTn-2sl6Z-" 97 | } 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": { 103 | "colab": { 104 | "base_uri": "https://localhost:8080/" 105 | }, 106 | "id": "yq_37frYCdgi", 107 | "outputId": "65e56e9a-6fb7-4f6c-eaab-d50139235253" 108 | }, 109 | "outputs": [ 110 | { 111 | "output_type": "stream", 112 | "name": "stdout", 113 | "text": [ 114 | "Enter your guess: 50\n", 115 | "You guessed it wrong! Enter a smaller number\n", 116 | "Enter your guess: 25\n", 117 | "You guessed it wrong! Enter a larger number\n", 118 | "Enter your guess: 37\n", 119 | "You guessed it right!\n", 120 | "You guessed the number in 3 guesses\n", 121 | "You have just broken the high score!\n" 122 | ] 123 | } 124 | ], 125 | "source": [ 126 | "import random\n", 127 | "randNumber = random.randint(1, 100)\n", 128 | "userGuess = None # becasue when we enter the loop we have not guessed anything\n", 129 | "guesses = 0 # becasue we have not guessed anything \n", 130 | "\n", 131 | "while(userGuess != randNumber): # this loop will continue untill the user has not guessed the number\n", 132 | " userGuess = int(input(\"Enter your guess: \"))\n", 133 | " guesses += 1 # this will increment the guesses by 1 everytime the user guesses\n", 134 | " if(userGuess==randNumber):\n", 135 | " print(\"You guessed it right!\")\n", 136 | " else:\n", 137 | " if(userGuess>randNumber):\n", 138 | " print(\"You guessed it wrong! Enter a smaller number\")\n", 139 | " else:\n", 140 | " print(\"You guessed it wrong! Enter a larger number\")\n", 141 | "\n", 142 | "print(f\"You guessed the number in {guesses} guesses\")\n", 143 | "\n", 144 | "with open(\"/content/hiscore.txt\", \"r\") as f:\n", 145 | " hiscore = int(f.read())\n", 146 | "\n", 147 | "if(guesses][twitter]\n", 162 | "[][linkedin]\n", 163 | "[][StackExchange AI]\n", 164 | "\n", 165 | "[twitter]: https://twitter.com/F4izy\n", 166 | "[linkedin]: https://www.linkedin.com/in/mohd-faizy/\n", 167 | "[StackExchange AI]: https://ai.stackexchange.com/users/36737/cypher" 168 | ], 169 | "metadata": { 170 | "id": "oltoRuqUzU6e" 171 | } 172 | } 173 | ] 174 | } -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/08_Student_Library_System.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["#
📕Student Library System📚
"],"metadata":{"id":"u-xbAvTyG91w"}},{"cell_type":"markdown","source":["Implement a student library system using `OPP's` where students can borrow a book from the list of book catalog.\n","\n","Create a separate library and student class. Your program must be menu driven. you are free to choose method's and attributes of your choice to implement this functionality."],"metadata":{"id":"kGnQHjs4HmY8"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"drZP6jnmG7TN"},"outputs":[],"source":["class Library:\n"," def __init__(self, listOfBooks):\n"," self.books = listOfBooks\n","\n"," def displayAvailableBooks(self):\n"," print(\"Books present in this library are: \")\n"," for book in self.books: \n"," print(\" *\" + book)\n"," \n"," def borrowBook(self, bookName):\n"," if bookName in self.books:\n"," print(f\"You have been issued {bookName}. Please keep it safe and return it within 30 days\")\n"," self.books.remove(bookName)\n"," return True\n"," else:\n"," print(\"Sorry, This book is either not available or has already been issued to someone else. Please wait until the book is available\")\n"," return False\n","\n"," def returnBook(self, bookName):\n"," self.books.append(bookName)\n"," print(\"Thanks for returning this book! Hope you enjoyed reading it. Have a great day ahead!\")\n","\n","class Student: \n"," def requestBook(self):\n"," self.book = input(\"Enter the name of the book you want to borrow: \")\n"," return self.book\n","\n"," def returnBook(self):\n"," self.book = input(\"Enter the name of the book you want to return: \")\n"," return self.book\n"," \n","\n","if __name__ == \"__main__\":\n"," centraLibrary = Library([\"Algorithms\", \"Django\", \"Clrs\", \"Python Notes\"])\n"," student = Student()\n"," # centraLibrary.displayAvailableBooks()\n"," while(True):\n"," welcomeMsg = '''\\n ====== Welcome to Central Library ======\n"," Please choose an option:\n"," 1. List all the books\n"," 2. Request a book\n"," 3. Add/Return a book\n"," 4. Exit the Library\n"," '''\n"," print(welcomeMsg)\n"," a = int(input(\"Enter a choice: \"))\n"," if a == 1:\n"," centraLibrary.displayAvailableBooks()\n"," elif a == 2:\n"," centraLibrary.borrowBook(student.requestBook())\n"," elif a == 3:\n"," centraLibrary.returnBook(student.returnBook())\n"," elif a == 4:\n"," print(\"Thanks for choosing Central Library. Have a great day ahead!\")\n"," exit()\n"," else:\n"," print(\"Invalid Choice!\")\n","\n"," "]}]} -------------------------------------------------------------------------------- /04_Python_Projects(Basic)/09_Snake_Water_Gun.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "u-xbAvTyG91w" 7 | }, 8 | "source": [ 9 | "#
Snake🐍Water💧Gun🔫
" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": { 15 | "id": "LHECf4Sr8tt3" 16 | }, 17 | "source": [ 18 | "- **Hands Up:** Players show one hand forming either a snake , water , or gun .\n", 19 | "- **Who Wins?**\n", 20 | " - Snake drinks water (Snake wins over Water).\n", 21 | " - Water douses gun (Water wins over Gun).\n", 22 | " - Gun shoots snake (Gun wins over Snake).\n", 23 | "- **Tie?** If both players choose the same symbol, it's a draw and you play again." 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "source": [ 29 | "import random\n", 30 | "\n", 31 | "def check(comp, user):\n", 32 | " if comp ==user:\n", 33 | " return 0\n", 34 | "\n", 35 | " if(comp == 0 and user ==1):\n", 36 | " return -1\n", 37 | "\n", 38 | " if(comp == 1 and user ==2):\n", 39 | " return -1\n", 40 | "\n", 41 | " if(comp == 2 and user == 0):\n", 42 | " return -1\n", 43 | "\n", 44 | " return 1\n", 45 | "\n", 46 | "\n", 47 | "comp = random.randint(0, 2)\n", 48 | "user = int(input(\"0 for Snake, 1 for water and 2 for Gun:\\n\"))\n", 49 | "\n", 50 | "score = check(comp, user)\n", 51 | "\n", 52 | "print(\"You: \", user)\n", 53 | "print(\"Computer: \", comp)\n", 54 | "\n", 55 | "if(score == 0):\n", 56 | " print(\"Its a draw\")\n", 57 | "elif (score == -1):\n", 58 | " print(\"You Lose\")\n", 59 | "else:\n", 60 | " print(\"You Won\")" 61 | ], 62 | "metadata": { 63 | "colab": { 64 | "base_uri": "https://localhost:8080/" 65 | }, 66 | "id": "YuYihPuF8uu5", 67 | "outputId": "6d8df43e-41e4-4c3d-9d82-6cf4ea3acc59" 68 | }, 69 | "execution_count": 1, 70 | "outputs": [ 71 | { 72 | "output_type": "stream", 73 | "name": "stdout", 74 | "text": [ 75 | "0 for Snake, 1 for water and 2 for Gun:\n", 76 | "1\n", 77 | "You: 1\n", 78 | "Computer: 2\n", 79 | "You Won\n" 80 | ] 81 | } 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "metadata": { 88 | "id": "drZP6jnmG7TN", 89 | "outputId": "d681e6a4-49c5-484c-c6d5-3764fabd8f1a" 90 | }, 91 | "outputs": [ 92 | { 93 | "name": "stdout", 94 | "output_type": "stream", 95 | "text": [ 96 | "You chose: s\n", 97 | "Computer chose: w\n", 98 | "You win!\n" 99 | ] 100 | } 101 | ], 102 | "source": [ 103 | "import random\n", 104 | "\n", 105 | "def get_user_choice():\n", 106 | " valid_choices = ['s', 'w', 'g']\n", 107 | " while True:\n", 108 | " user_choice = input(\"Enter 's' for Snake, 'w' for Water, or 'g' for Gun: \")\n", 109 | " if user_choice.lower() in valid_choices:\n", 110 | " return user_choice.lower()\n", 111 | " else:\n", 112 | " print(\"Invalid input. Please enter 's', 'w', or 'g'.\")\n", 113 | "\n", 114 | "\n", 115 | "def check_win(user_choice, computer_choice):\n", 116 | " win_conditions = {\n", 117 | " 's': 'w', # Snake beats Water\n", 118 | " 'w': 'g', # Water beats Gun\n", 119 | " 'g': 's' # Gun beats Snake\n", 120 | " }\n", 121 | "\n", 122 | " if user_choice == computer_choice:\n", 123 | " return None # Tie\n", 124 | " elif win_conditions[user_choice] == computer_choice:\n", 125 | " return True # User wins\n", 126 | " else:\n", 127 | " return False # Computer wins\n", 128 | "\n", 129 | "\n", 130 | "def play_game():\n", 131 | " choices = ['s', 'w', 'g']\n", 132 | " computer_choice = random.choice(choices)\n", 133 | "\n", 134 | " user_choice = get_user_choice()\n", 135 | "\n", 136 | " print(f\"You chose: {user_choice}\")\n", 137 | " print(f\"Computer chose: {computer_choice}\")\n", 138 | "\n", 139 | " result = check_win(user_choice, computer_choice)\n", 140 | "\n", 141 | " if result is None:\n", 142 | " print(\"It's a tie!\")\n", 143 | " elif result:\n", 144 | " print(\"You win!\")\n", 145 | " else:\n", 146 | " print(\"You lose.\")\n", 147 | "\n", 148 | "\n", 149 | "def main():\n", 150 | " while True:\n", 151 | " play_game()\n", 152 | " play_again = input(\"Play again? (y/n): \")\n", 153 | " if play_again.lower() not in ('y', 'yes'):\n", 154 | " break\n", 155 | "\n", 156 | "if __name__ == \"__main__\":\n", 157 | " main()" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": { 163 | "id": "Z1SvYf8R8tt6" 164 | }, 165 | "source": [ 166 | "**What is this???**\n", 167 | "\n", 168 | "```python\n", 169 | "if __name__ == \"__main__\":\n", 170 | " main()\n", 171 | "```\n", 172 | "\n", 173 | "[Click here](https://www.youtube.com/watch?v=o4XveLyI6YU&loop=0)" 174 | ] 175 | } 176 | ], 177 | "metadata": { 178 | "colab": { 179 | "provenance": [] 180 | }, 181 | "kernelspec": { 182 | "display_name": "Python 3", 183 | "name": "python3" 184 | }, 185 | "language_info": { 186 | "codemirror_mode": { 187 | "name": "ipython", 188 | "version": 3 189 | }, 190 | "file_extension": ".py", 191 | "mimetype": "text/x-python", 192 | "name": "python", 193 | "nbconvert_exporter": "python", 194 | "pygments_lexer": "ipython3", 195 | "version": "3.11.2" 196 | } 197 | }, 198 | "nbformat": 4, 199 | "nbformat_minor": 0 200 | } -------------------------------------------------------------------------------- /05_Python_Projects(Intermediate)/py.py: -------------------------------------------------------------------------------- 1 | print("Hello world") -------------------------------------------------------------------------------- /06_Python_Projects(Advance)/py.py: -------------------------------------------------------------------------------- 1 | print("Hello world") -------------------------------------------------------------------------------- /07_Python_PracticeSet/03_Prob_Py_Part_3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "7sIXGj0EJFas" 7 | }, 8 | "source": [ 9 | "---\n", 10 | "\n", 11 | "

Practice-Sheet-2024

\n", 12 | "
\n", 13 | "\n", 14 | "---" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": { 21 | "id": "FrTPjbxt_vYY" 22 | }, 23 | "outputs": [], 24 | "source": [ 25 | "pip -q install pyttsx3" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "source": [ 31 | "**Text to Speech**" 32 | ], 33 | "metadata": { 34 | "id": "xl1i6D4pLtt_" 35 | } 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": { 41 | "id": "qEi1-5Mw_vYZ" 42 | }, 43 | "outputs": [], 44 | "source": [ 45 | "import pyttsx3\n", 46 | "\n", 47 | "engine = pyttsx3.init()\n", 48 | "engine.say(\"I love Python\")\n", 49 | "engine.runAndWait()" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "metadata": { 56 | "colab": { 57 | "base_uri": "https://localhost:8080/" 58 | }, 59 | "id": "nDnxs0rU_vYa", 60 | "outputId": "0fd0ccda-663e-4c5b-8e24-80ee3ef3fe9f" 61 | }, 62 | "outputs": [ 63 | { 64 | "output_type": "stream", 65 | "name": "stdout", 66 | "text": [ 67 | "['README.md', 'anscombe.json', 'mnist_train_small.csv', 'california_housing_train.csv', 'california_housing_test.csv', 'mnist_test.csv']\n" 68 | ] 69 | } 70 | ], 71 | "source": [ 72 | "import os\n", 73 | "\n", 74 | "# Select the directory whose content you want to list\n", 75 | "directory_path = '/content/sample_data'\n", 76 | "\n", 77 | "# Use the os module to list the directory content\n", 78 | "contents = os.listdir(directory_path)\n", 79 | "\n", 80 | "# Print the contents of the directory\n", 81 | "print(contents)" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "source": [ 87 | "## **Loops**" 88 | ], 89 | "metadata": { 90 | "id": "av9BCs2vCKCM" 91 | } 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "metadata": { 96 | "id": "sFGoXttT_vYb" 97 | }, 98 | "source": [ 99 | "**1. Write a program to print multiplication table of a given number using for loop.**" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "metadata": { 106 | "colab": { 107 | "base_uri": "https://localhost:8080/" 108 | }, 109 | "id": "6JXOWZKU_vYb", 110 | "outputId": "a54a0eb3-544a-4019-b673-db71cbd4599d" 111 | }, 112 | "outputs": [ 113 | { 114 | "output_type": "stream", 115 | "name": "stdout", 116 | "text": [ 117 | "Enter a Number: 9\n", 118 | "9 X 1 = 9\n", 119 | "9 X 2 = 18\n", 120 | "9 X 3 = 27\n", 121 | "9 X 4 = 36\n", 122 | "9 X 5 = 45\n", 123 | "9 X 6 = 54\n", 124 | "9 X 7 = 63\n", 125 | "9 X 8 = 72\n", 126 | "9 X 9 = 81\n", 127 | "9 X 10 = 90\n" 128 | ] 129 | } 130 | ], 131 | "source": [ 132 | "n = int(input(\"Enter the Number: \"))\n", 133 | "\n", 134 | "for i in range(1, 11):\n", 135 | " print(f\"{n} X {i} = {i*n}\")" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "source": [ 141 | "**2. Write a program to greet all the person names stored in a list `l` and which starts with `S`.**\n", 142 | "\n", 143 | "- `l = [\"Harry\", \"Soham\", \"Sachin\", \"Rahul\"]`" 144 | ], 145 | "metadata": { 146 | "id": "M5y0a8B9BXCG" 147 | } 148 | }, 149 | { 150 | "cell_type": "code", 151 | "source": [ 152 | "l = [\"Harry\", \"Soham\", \"Sachin\", \"Rahul\"]\n", 153 | "\n", 154 | "for name in l:\n", 155 | " if (name.startswith(\"S\")):\n", 156 | " print(f\"Hello {name}\")" 157 | ], 158 | "metadata": { 159 | "colab": { 160 | "base_uri": "https://localhost:8080/" 161 | }, 162 | "id": "YRaoHp4zAC00", 163 | "outputId": "94a61f68-cf0b-4322-b12c-90666f291f5a" 164 | }, 165 | "execution_count": null, 166 | "outputs": [ 167 | { 168 | "output_type": "stream", 169 | "name": "stdout", 170 | "text": [ 171 | "Hello Soham\n", 172 | "Hello Sachin\n" 173 | ] 174 | } 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "source": [ 180 | "**3. Write a program to print multiplication table of a given number using while loop.**" 181 | ], 182 | "metadata": { 183 | "id": "8aFWU3QNCdwM" 184 | } 185 | }, 186 | { 187 | "cell_type": "code", 188 | "source": [ 189 | "n = int(input(\"Enter the Number: \"))\n", 190 | "\n", 191 | "i=1\n", 192 | "\n", 193 | "while i<11:\n", 194 | " print(f\"{n} X {i} = {n*i}\")\n", 195 | " i += 1" 196 | ], 197 | "metadata": { 198 | "colab": { 199 | "base_uri": "https://localhost:8080/" 200 | }, 201 | "id": "LqA9AW1CBtEt", 202 | "outputId": "31f3762d-0ec7-4314-951c-40f622cc2d08" 203 | }, 204 | "execution_count": null, 205 | "outputs": [ 206 | { 207 | "output_type": "stream", 208 | "name": "stdout", 209 | "text": [ 210 | "Enter a Number: 5\n", 211 | "5 X 1 = 5\n", 212 | "5 X 2 = 10\n", 213 | "5 X 3 = 15\n", 214 | "5 X 4 = 20\n", 215 | "5 X 5 = 25\n", 216 | "5 X 6 = 30\n", 217 | "5 X 7 = 35\n", 218 | "5 X 8 = 40\n", 219 | "5 X 9 = 45\n", 220 | "5 X 10 = 50\n" 221 | ] 222 | } 223 | ] 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "source": [ 228 | "**4. Write a program to find whether a given number is prime or not.**" 229 | ], 230 | "metadata": { 231 | "id": "tCq7na_iDiKl" 232 | } 233 | }, 234 | { 235 | "cell_type": "code", 236 | "source": [ 237 | "n = int(input(\"Enter the Number: \"))\n", 238 | "\n", 239 | "for i in range(2, n):\n", 240 | " if (n%i) == 0:\n", 241 | " print(\"number is not prime\")\n", 242 | " break\n", 243 | "else:\n", 244 | " print(\"number is prime\")" 245 | ], 246 | "metadata": { 247 | "colab": { 248 | "base_uri": "https://localhost:8080/" 249 | }, 250 | "id": "72CmCZpHC-g1", 251 | "outputId": "4c919df2-9a42-45d2-99c8-532647ec0029" 252 | }, 253 | "execution_count": null, 254 | "outputs": [ 255 | { 256 | "output_type": "stream", 257 | "name": "stdout", 258 | "text": [ 259 | "Enter a Number: 11\n", 260 | "number is prime\n" 261 | ] 262 | } 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "source": [ 268 | "**5. Write a program to find the sum of first n natural numbers using while loop.**" 269 | ], 270 | "metadata": { 271 | "id": "STVxFDjWFFHe" 272 | } 273 | }, 274 | { 275 | "cell_type": "code", 276 | "source": [ 277 | "n = int(input(\"Enter the Number: \"))\n", 278 | "\n", 279 | "i = 1\n", 280 | "sum = 0 #Note: for addition, we initialize the sum with zero.\n", 281 | "\n", 282 | "while(i<=n):\n", 283 | " sum += i\n", 284 | " i += 1\n", 285 | "\n", 286 | "print(sum)" 287 | ], 288 | "metadata": { 289 | "colab": { 290 | "base_uri": "https://localhost:8080/" 291 | }, 292 | "id": "R8dJ_dfWD_8V", 293 | "outputId": "978710fc-b7c5-4414-8ad9-993f31e029b2" 294 | }, 295 | "execution_count": null, 296 | "outputs": [ 297 | { 298 | "output_type": "stream", 299 | "name": "stdout", 300 | "text": [ 301 | "Enter the Number: 4\n", 302 | "10\n" 303 | ] 304 | } 305 | ] 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "source": [ 310 | "**Arithmetic mean**" 311 | ], 312 | "metadata": { 313 | "id": "uRNjS2ICKAp5" 314 | } 315 | }, 316 | { 317 | "cell_type": "code", 318 | "source": [ 319 | "n = int(input(\"Enter the Number: \"))\n", 320 | "\n", 321 | "i = 1\n", 322 | "sum = 0 # Note: for addition, we initialize the sum with zero.\n", 323 | "\n", 324 | "while(i <= n):\n", 325 | " sum += i\n", 326 | " i += 1\n", 327 | "\n", 328 | "arithmetic_mean = sum / n\n", 329 | "print(f\"Arithmetic Mean is {sum}/{n} =\", arithmetic_mean)\n" 330 | ], 331 | "metadata": { 332 | "colab": { 333 | "base_uri": "https://localhost:8080/" 334 | }, 335 | "id": "y_evow5_JlHW", 336 | "outputId": "5dd67bfc-f6ab-4470-8e06-de771bf36029" 337 | }, 338 | "execution_count": null, 339 | "outputs": [ 340 | { 341 | "output_type": "stream", 342 | "name": "stdout", 343 | "text": [ 344 | "Enter the Number: 5\n", 345 | "Arithmetic Mean is 15/5 = 3.0\n" 346 | ] 347 | } 348 | ] 349 | }, 350 | { 351 | "cell_type": "markdown", 352 | "source": [ 353 | "**6. Write a program to calculate the factorial of a given number using for loop.**" 354 | ], 355 | "metadata": { 356 | "id": "n2z10iXmGDPH" 357 | } 358 | }, 359 | { 360 | "cell_type": "code", 361 | "source": [ 362 | "# 5! = 1 X 2 X 3 X 4 X 5\n", 363 | "\n", 364 | "n = int(input(\"Enter the Number: \"))\n", 365 | "\n", 366 | "product = 1 # Note: for product, we initialize the sum with one.\n", 367 | "\n", 368 | "for i in range(1, n+1):\n", 369 | " product = product * i\n", 370 | "\n", 371 | "print(product)" 372 | ], 373 | "metadata": { 374 | "colab": { 375 | "base_uri": "https://localhost:8080/" 376 | }, 377 | "id": "QcqdHM2sFthm", 378 | "outputId": "9cc6813b-dce0-48b7-b8bb-9f0b501f62d2" 379 | }, 380 | "execution_count": null, 381 | "outputs": [ 382 | { 383 | "output_type": "stream", 384 | "name": "stdout", 385 | "text": [ 386 | "Enter the Number: 6\n", 387 | "720\n" 388 | ] 389 | } 390 | ] 391 | }, 392 | { 393 | "cell_type": "markdown", 394 | "source": [ 395 | "**8. Write a program to print the following star pattern.**\n", 396 | "\n", 397 | "- for `n = 5`\n", 398 | "\n", 399 | "```\n", 400 | " * space=4, star=1\n", 401 | " *** space=3, star=3\n", 402 | " ***** space=2, star=5\n", 403 | " ******* space=1, star=7\n", 404 | "********* space=0, star=9\n", 405 | "```\n" 406 | ], 407 | "metadata": { 408 | "id": "XYRCBzwxIyz1" 409 | } 410 | }, 411 | { 412 | "cell_type": "code", 413 | "source": [ 414 | "n = int(input(\"Enter the Number: \"))\n", 415 | "\n", 416 | "for i in range(1, n+1):\n", 417 | " print(\" \"*(n-i), end=\"\") # space\n", 418 | " print(\"*\"*(2*i-1), end=\"\") # star ~ odd number\n", 419 | " print(\"\")" 420 | ], 421 | "metadata": { 422 | "colab": { 423 | "base_uri": "https://localhost:8080/" 424 | }, 425 | "id": "hglkLHELJSb1", 426 | "outputId": "6eba48e5-76bb-4372-a671-0949457f0cfd" 427 | }, 428 | "execution_count": null, 429 | "outputs": [ 430 | { 431 | "output_type": "stream", 432 | "name": "stdout", 433 | "text": [ 434 | "Enter the Number: 5\n", 435 | " *\n", 436 | " ***\n", 437 | " *****\n", 438 | " *******\n", 439 | "*********\n" 440 | ] 441 | } 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "source": [ 447 | "**8. Write a program to print the following star pattern.**\n", 448 | "\n", 449 | "- for `n = 5`\n", 450 | "\n", 451 | "```\n", 452 | "* space=0, star=1\n", 453 | "*** space=0, star=3\n", 454 | "***** space=0, star=5\n", 455 | "******* space=0, star=7\n", 456 | "********* space=0, star=9\n", 457 | "```" 458 | ], 459 | "metadata": { 460 | "id": "WY-UaPWBJFu1" 461 | } 462 | }, 463 | { 464 | "cell_type": "code", 465 | "source": [ 466 | "n = int(input(\"Enter the Number: \"))\n", 467 | "\n", 468 | "for i in range(1, n+1):\n", 469 | " print(\" \", end=\"\") # space\n", 470 | " print(\"*\"*(2*i-1), end=\"\") # star ~ odd number\n", 471 | " print(\"\")" 472 | ], 473 | "metadata": { 474 | "colab": { 475 | "base_uri": "https://localhost:8080/" 476 | }, 477 | "id": "-EWAMd07JTF1", 478 | "outputId": "6000bbce-90dc-4af6-a259-5e3e87502899" 479 | }, 480 | "execution_count": null, 481 | "outputs": [ 482 | { 483 | "output_type": "stream", 484 | "name": "stdout", 485 | "text": [ 486 | "Enter the Number: 5\n", 487 | " *\n", 488 | " ***\n", 489 | " *****\n", 490 | " *******\n", 491 | " *********\n" 492 | ] 493 | } 494 | ] 495 | }, 496 | { 497 | "cell_type": "markdown", 498 | "source": [ 499 | "**9. Write a program to print the following star pattern.**\n", 500 | "\n", 501 | "- for `n = 4`\n", 502 | "\n", 503 | "```\n", 504 | " * space=3, star=1\n", 505 | " *** space=2, star=3\n", 506 | " ***** space=1, star=5\n", 507 | "******* space=0, star=7\n", 508 | " ***** space=1, star=5\n", 509 | " *** space=2, star=3\n", 510 | " * space=3, star=1\n", 511 | "\n", 512 | "```\n" 513 | ], 514 | "metadata": { 515 | "id": "ywoIq4aQUpfP" 516 | } 517 | }, 518 | { 519 | "cell_type": "code", 520 | "source": [ 521 | "n = int(input(\"Enter the Number: \"))\n", 522 | "\n", 523 | "# Upper part of the pattern\n", 524 | "for i in range(1, n+1):\n", 525 | " print(\" \"*(n-i), end=\"\")\n", 526 | " print(\"*\"*(2*i-1), end=\"\")\n", 527 | " print(\"\")\n", 528 | "\n", 529 | "# Lower part of the pattern\n", 530 | "for j in range(n-1, 0, -1):\n", 531 | " print(\" \"*(n-j), end=\"\")\n", 532 | " print(\"*\"*(2*j-1), end=\"\")\n", 533 | " print(\"\")\n" 534 | ], 535 | "metadata": { 536 | "colab": { 537 | "base_uri": "https://localhost:8080/" 538 | }, 539 | "id": "cVrHq2C0UpNg", 540 | "outputId": "80159be7-12de-4e11-8f3a-a354933c3c08" 541 | }, 542 | "execution_count": null, 543 | "outputs": [ 544 | { 545 | "output_type": "stream", 546 | "name": "stdout", 547 | "text": [ 548 | "Enter the Number: 4\n", 549 | " *\n", 550 | " ***\n", 551 | " *****\n", 552 | "*******\n", 553 | " *****\n", 554 | " ***\n", 555 | " *\n" 556 | ] 557 | } 558 | ] 559 | }, 560 | { 561 | "cell_type": "markdown", 562 | "source": [ 563 | "**10. Write a program to print the following star pattern.**\n", 564 | "\n", 565 | "```\n", 566 | "***\n", 567 | "* *\n", 568 | "***\n", 569 | "```\n", 570 | "\n", 571 | "for `n = 3`.\n", 572 | "\n", 573 | "```\n", 574 | "****\n", 575 | "* *\n", 576 | "* *\n", 577 | "****\n", 578 | "```\n", 579 | "\n", 580 | "for `n = 4`." 581 | ], 582 | "metadata": { 583 | "id": "9h8svRffJGsV" 584 | } 585 | }, 586 | { 587 | "cell_type": "code", 588 | "source": [ 589 | "n = int(input(\"Enter the Number: \"))\n", 590 | "\n", 591 | "# Upper part of the pattern\n", 592 | "for i in range(1, n+1):\n", 593 | " if(i==1 or i==n):\n", 594 | " print(\"*\"*n, end=\"\")\n", 595 | " else:\n", 596 | " print(\"*\", end=\"\")\n", 597 | " print(\" \"*(n-2), end=\"\")\n", 598 | " print(\"*\", end=\"\")\n", 599 | " print(\"\")" 600 | ], 601 | "metadata": { 602 | "colab": { 603 | "base_uri": "https://localhost:8080/" 604 | }, 605 | "id": "V1Jk0xQtHFTW", 606 | "outputId": "869138a3-c953-4e30-ced7-d3d451fbf951" 607 | }, 608 | "execution_count": null, 609 | "outputs": [ 610 | { 611 | "output_type": "stream", 612 | "name": "stdout", 613 | "text": [ 614 | "Enter the Number: 7\n", 615 | "*******\n", 616 | "* *\n", 617 | "* *\n", 618 | "* *\n", 619 | "* *\n", 620 | "* *\n", 621 | "*******\n" 622 | ] 623 | } 624 | ] 625 | }, 626 | { 627 | "cell_type": "markdown", 628 | "source": [ 629 | "**11. Write a program to print multiplication table of n using for loops in reversed order.**" 630 | ], 631 | "metadata": { 632 | "id": "HG1JHc4th3fu" 633 | } 634 | }, 635 | { 636 | "cell_type": "code", 637 | "source": [ 638 | "n = int(input(\"Enter the Number: \"))\n", 639 | "\n", 640 | "for i in range(1, 11):\n", 641 | " print(f\"{n} X {11-i} = {n*(11-i)}\")" 642 | ], 643 | "metadata": { 644 | "colab": { 645 | "base_uri": "https://localhost:8080/" 646 | }, 647 | "id": "A0CSSQzofU2W", 648 | "outputId": "c9bc060f-cdd1-4d96-c003-f8b76126d3f2" 649 | }, 650 | "execution_count": null, 651 | "outputs": [ 652 | { 653 | "output_type": "stream", 654 | "name": "stdout", 655 | "text": [ 656 | "Enter the Number: 689\n", 657 | "689 X 10 = 6890\n", 658 | "689 X 9 = 6201\n", 659 | "689 X 8 = 5512\n", 660 | "689 X 7 = 4823\n", 661 | "689 X 6 = 4134\n", 662 | "689 X 5 = 3445\n", 663 | "689 X 4 = 2756\n", 664 | "689 X 3 = 2067\n", 665 | "689 X 2 = 1378\n", 666 | "689 X 1 = 689\n" 667 | ] 668 | } 669 | ] 670 | }, 671 | { 672 | "cell_type": "code", 673 | "source": [], 674 | "metadata": { 675 | "id": "Pz_7XiSkiKPD" 676 | }, 677 | "execution_count": null, 678 | "outputs": [] 679 | } 680 | ], 681 | "metadata": { 682 | "colab": { 683 | "provenance": [], 684 | "toc_visible": true 685 | }, 686 | "kernelspec": { 687 | "display_name": "Python 3", 688 | "name": "python3" 689 | }, 690 | "language_info": { 691 | "codemirror_mode": { 692 | "name": "ipython", 693 | "version": 3 694 | }, 695 | "file_extension": ".py", 696 | "mimetype": "text/x-python", 697 | "name": "python", 698 | "nbconvert_exporter": "python", 699 | "pygments_lexer": "ipython3", 700 | "version": "3.11.2" 701 | } 702 | }, 703 | "nbformat": 4, 704 | "nbformat_minor": 0 705 | } -------------------------------------------------------------------------------- /08_Advance_Python/module.py: -------------------------------------------------------------------------------- 1 | def greet(name): 2 | print(f"Hello!, {name}") 3 | 4 | print(__name__) 5 | if __name__ == "__main__": 6 | n = input("Enter the name\n") 7 | greet(n) -------------------------------------------------------------------------------- /09_New_in_Python/03_Speed_Comparison.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "SpeedComparison.ipynb", 7 | "provenance": [], 8 | "toc_visible": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | } 14 | }, 15 | "cells": [ 16 | { 17 | "metadata": { 18 | "id": "OK0YyVunripT" 19 | }, 20 | "cell_type": "markdown", 21 | "source": [ 22 | "#CREATION \n" 23 | ] 24 | }, 25 | { 26 | "metadata": { 27 | "id": "7R1sV-R0rnNK" 28 | }, 29 | "cell_type": "markdown", 30 | "source": [ 31 | "## LIST" 32 | ] 33 | }, 34 | { 35 | "metadata": { 36 | "id": "FD80-eE6rzE7" 37 | }, 38 | "cell_type": "markdown", 39 | "source": [ 40 | "for our list, we will first create a dummy list which will in turn be use to map the list which is put under the speed test" 41 | ] 42 | }, 43 | { 44 | "metadata": { 45 | "id": "yo3y39UzsBJB" 46 | }, 47 | "cell_type": "code", 48 | "source": [ 49 | "my_list=list(range(1000))" 50 | ], 51 | "execution_count": 1, 52 | "outputs": [] 53 | }, 54 | { 55 | "metadata": { 56 | "id": "ZTeQ_En_sKsi" 57 | }, 58 | "cell_type": "markdown", 59 | "source": [ 60 | "For a suitable end result we are going to take average of time for 10000 lists" 61 | ] 62 | }, 63 | { 64 | "metadata": { 65 | "id": "wP4Lf7v-sH8H" 66 | }, 67 | "cell_type": "code", 68 | "source": [ 69 | "sumlist=0 #to save the final result" 70 | ], 71 | "execution_count": 2, 72 | "outputs": [] 73 | }, 74 | { 75 | "metadata": { 76 | "id": "uqP57G1ls4Qh" 77 | }, 78 | "cell_type": "markdown", 79 | "source": [ 80 | "to calculate time we are going to use the help of package \"time\"" 81 | ] 82 | }, 83 | { 84 | "metadata": { 85 | "id": "ZO5zxPR3s3sP" 86 | }, 87 | "cell_type": "code", 88 | "source": [ 89 | "import time" 90 | ], 91 | "execution_count": 3, 92 | "outputs": [] 93 | }, 94 | { 95 | "metadata": { 96 | "id": "4_yY943atxu7" 97 | }, 98 | "cell_type": "markdown", 99 | "source": [ 100 | "Now we will create the list which is put under the speed test with the help of \"map\" function, the*** tic value*** marks the start of time and*** toc value*** marks the end of observation time" 101 | ] 102 | }, 103 | { 104 | "metadata": { 105 | "id": "ccxFw0XSs-Ob", 106 | "outputId": "9f48b2ab-45bd-4808-d2fd-6f21bb7fb65e", 107 | "colab": { 108 | "base_uri": "https://localhost:8080/" 109 | } 110 | }, 111 | "cell_type": "code", 112 | "source": [ 113 | "for i in range(10000):\n", 114 | " tic=time.time()\n", 115 | " my_ls=list(map(lambda x:x**2,my_list))\n", 116 | " toc=time.time()\n", 117 | " sumlist+=toc-tic\n", 118 | "print(\"value for list is : \",sumlist/10000)" 119 | ], 120 | "execution_count": 4, 121 | "outputs": [ 122 | { 123 | "output_type": "stream", 124 | "name": "stdout", 125 | "text": [ 126 | "value for list is : 0.0003192671537399292\n" 127 | ] 128 | } 129 | ] 130 | }, 131 | { 132 | "metadata": { 133 | "id": "VSf-dTcztJhM" 134 | }, 135 | "cell_type": "markdown", 136 | "source": [ 137 | "##Tuple" 138 | ] 139 | }, 140 | { 141 | "metadata": { 142 | "id": "ZwoqWTa8tMEI" 143 | }, 144 | "cell_type": "markdown", 145 | "source": [ 146 | "Similarly for tuple" 147 | ] 148 | }, 149 | { 150 | "metadata": { 151 | "id": "X4yroIF_tCzP" 152 | }, 153 | "cell_type": "code", 154 | "source": [ 155 | "sumtuple=0\n", 156 | "my_tuple=tuple(range(1000))" 157 | ], 158 | "execution_count": 5, 159 | "outputs": [] 160 | }, 161 | { 162 | "metadata": { 163 | "id": "9GKgprPYtQY_", 164 | "outputId": "bcb68156-f9cd-4d0e-e160-33c3ea4501c9", 165 | "colab": { 166 | "base_uri": "https://localhost:8080/" 167 | } 168 | }, 169 | "cell_type": "code", 170 | "source": [ 171 | "for i in range(10000):\n", 172 | " tic=time.time()\n", 173 | " myt=tuple(map(lambda x:x**2,my_tuple))\n", 174 | " toc=time.time()\n", 175 | " sumtuple+=toc-tic\n", 176 | "print(\"value for tuple is : \",sumtuple/10000)" 177 | ], 178 | "execution_count": 6, 179 | "outputs": [ 180 | { 181 | "output_type": "stream", 182 | "name": "stdout", 183 | "text": [ 184 | "value for tuple is : 0.0003726994037628174\n" 185 | ] 186 | } 187 | ] 188 | }, 189 | { 190 | "metadata": { 191 | "id": "W40lbD-FzE3I" 192 | }, 193 | "cell_type": "markdown", 194 | "source": [ 195 | "#Membership Testing" 196 | ] 197 | }, 198 | { 199 | "metadata": { 200 | "id": "pGrpp7gqz7dc" 201 | }, 202 | "cell_type": "markdown", 203 | "source": [ 204 | "## LIST" 205 | ] 206 | }, 207 | { 208 | "metadata": { 209 | "id": "pLJJgmShtSkD" 210 | }, 211 | "cell_type": "code", 212 | "source": [ 213 | "sumlist=0\n", 214 | "mylist=list(range(1000000))" 215 | ], 216 | "execution_count": 7, 217 | "outputs": [] 218 | }, 219 | { 220 | "metadata": { 221 | "id": "Jbx0AHSn0Bos", 222 | "outputId": "0f8eb4fa-28e6-4b06-a1e8-b841784f0cbf", 223 | "colab": { 224 | "base_uri": "https://localhost:8080/" 225 | } 226 | }, 227 | "cell_type": "code", 228 | "source": [ 229 | "for i in range(1000):\n", 230 | " tic=time.time()\n", 231 | " x=6666 in mylist\n", 232 | " x=(11111 in mylist)\n", 233 | " x=(1111111 in mylist)\n", 234 | " toc=time.time()\n", 235 | " sumlist+=toc-tic\n", 236 | "print(\"LIST TIME : \",sumlist/1000)" 237 | ], 238 | "execution_count": 8, 239 | "outputs": [ 240 | { 241 | "output_type": "stream", 242 | "name": "stdout", 243 | "text": [ 244 | "LIST TIME : 0.015630522966384886\n" 245 | ] 246 | } 247 | ] 248 | }, 249 | { 250 | "metadata": { 251 | "id": "fSc7e_iI1H4f" 252 | }, 253 | "cell_type": "markdown", 254 | "source": [ 255 | "##SET" 256 | ] 257 | }, 258 | { 259 | "metadata": { 260 | "id": "IruMtv9Y0aet" 261 | }, 262 | "cell_type": "code", 263 | "source": [ 264 | "myset=set(range(1000000))\n", 265 | "sumset=0" 266 | ], 267 | "execution_count": 9, 268 | "outputs": [] 269 | }, 270 | { 271 | "metadata": { 272 | "id": "0cs5GA_O0xAF", 273 | "outputId": "0aa7ebeb-c2a8-4675-9a4f-36677f2ffff6", 274 | "colab": { 275 | "base_uri": "https://localhost:8080/" 276 | } 277 | }, 278 | "cell_type": "code", 279 | "source": [ 280 | "for i in range(1000):\n", 281 | " tic=time.time()\n", 282 | " x=6666 in myset\n", 283 | " x=(11111 in myset)\n", 284 | " x=(1111111 in myset)\n", 285 | " toc=time.time()\n", 286 | " sumset+=toc-tic\n", 287 | "print(\"SET TIME : \",sumset/1000)" 288 | ], 289 | "execution_count": 10, 290 | "outputs": [ 291 | { 292 | "output_type": "stream", 293 | "name": "stdout", 294 | "text": [ 295 | "SET TIME : 8.132457733154297e-07\n" 296 | ] 297 | } 298 | ] 299 | } 300 | ] 301 | } -------------------------------------------------------------------------------- /09_New_in_Python/04_Walrus_Operator.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "toc_visible": true 8 | }, 9 | "kernelspec": { 10 | "name": "python3", 11 | "display_name": "Python 3" 12 | }, 13 | "language_info": { 14 | "name": "python" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "code", 20 | "source": [ 21 | "# walrus operator :=\n", 22 | "# new to Python 3.8\n", 23 | "# assignment expression aka walrus operator\n", 24 | "# assigns values to variables as part of a larger expression" 25 | ], 26 | "metadata": { 27 | "id": "sZZKTbCR_o5Y" 28 | }, 29 | "execution_count": 5, 30 | "outputs": [] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "source": [ 35 | "# Without walrus operator\n", 36 | "numbers = [1, 2, 3, 4, 5]\n", 37 | "evens = []\n", 38 | "for num in numbers:\n", 39 | " if num % 2 == 0:\n", 40 | " evens.append(num)\n", 41 | "print(evens)" 42 | ], 43 | "metadata": { 44 | "colab": { 45 | "base_uri": "https://localhost:8080/" 46 | }, 47 | "id": "WSg8Wn0zALAQ", 48 | "outputId": "4603f21f-9ac4-4def-8c4d-ad20ccfd08ed" 49 | }, 50 | "execution_count": 6, 51 | "outputs": [ 52 | { 53 | "output_type": "stream", 54 | "name": "stdout", 55 | "text": [ 56 | "[2, 4]\n" 57 | ] 58 | } 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "source": [ 64 | "# With walrus operator\n", 65 | "numbers = [1, 2, 3, 4, 5]\n", 66 | "evens = [num for num in numbers if (remainder := num % 2) == 0]\n", 67 | "print(evens)\n", 68 | "print(remainder) # This will print the value of remainder outside the list comprehension" 69 | ], 70 | "metadata": { 71 | "colab": { 72 | "base_uri": "https://localhost:8080/" 73 | }, 74 | "id": "7C6hUY37AKKw", 75 | "outputId": "0c1cf607-2119-421c-845f-ab1e525637d5" 76 | }, 77 | "execution_count": 7, 78 | "outputs": [ 79 | { 80 | "output_type": "stream", 81 | "name": "stdout", 82 | "text": [ 83 | "[2, 4]\n", 84 | "1\n" 85 | ] 86 | } 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": 8, 92 | "metadata": { 93 | "colab": { 94 | "base_uri": "https://localhost:8080/" 95 | }, 96 | "id": "BBomFredWaJZ", 97 | "outputId": "c97f8c26-14fd-476c-8a6e-7b6f806bf5d2" 98 | }, 99 | "outputs": [ 100 | { 101 | "output_type": "stream", 102 | "name": "stdout", 103 | "text": [ 104 | "With Python 3.8 Walrus Operator:\n", 105 | "Found name: \"rahul\"\n", 106 | "Found name: \"rohit\"\n", 107 | "Found name: \"ram\"\n", 108 | "Found name: \"ravan\"\n", 109 | "Without Walrus operator:\n", 110 | "Found name: \"rahul\"\n", 111 | "Found name: \"rohit\"\n", 112 | "Found name: \"ram\"\n", 113 | "Found name: \"ravan\"\n" 114 | ] 115 | } 116 | ], 117 | "source": [ 118 | "sample_data = [\n", 119 | " {\"userId\": 1, \"name\": \"rahul\", \"completed\": False},\n", 120 | " {\"userId\": 1, \"name\": \"rohit\", \"completed\": False},\n", 121 | " {\"userId\": 1, \"name\": \"ram\", \"completed\": False},\n", 122 | " {\"userId\": 1, \"name\": \"ravan\", \"completed\": True}\n", 123 | "]\n", 124 | "\n", 125 | "print(\"With Python 3.8 Walrus Operator:\")\n", 126 | "for entry in sample_data:\n", 127 | " if name := entry.get(\"name\"):\n", 128 | " print(f'Found name: \"{name}\"')\n", 129 | "\n", 130 | "print(\"Without Walrus operator:\")\n", 131 | "for entry in sample_data:\n", 132 | " name = entry.get(\"name\")\n", 133 | " if name:\n", 134 | " print(f'Found name: \"{name}\"')\n" 135 | ] 136 | } 137 | ] 138 | } -------------------------------------------------------------------------------- /09_New_in_Python/05_Match_Placeholder___regex.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"Shqn5p58bY9Z"},"outputs":[],"source":["#check python version\n","import sys\n","print(sys.version)\n","!python3 --version\n","!python --version"]},{"cell_type":"markdown","metadata":{"id":"IFKzDQuXkibM"},"source":["## Placeholder `_`"]},{"cell_type":"markdown","metadata":{"id":"8X-erH5wiy9C"},"source":["The underscore `(_)` is a special character in Python that has various uses. For example, it is commonly used as a placeholder for an unused variable, or to represent the result of the last executed expression when used in the interactive interpreter.\n","\n","Here is an example of how the underscore can be used as a placeholder for an unused variable:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"DAfvc-FYj7WM"},"outputs":[],"source":["# Assign the value 10 to the variable `x`\n","x = 10\n","\n","# This expression is not assigned to any variable, so the result is discarded\n","# and the underscore is used as a placeholder\n","_ = x * 2\n","\n","# At this point, the value of `x` is still 10, since the underscore is not a\n","# reference to the result of the previous expression\n","print(x) # Output: 10"]},{"cell_type":"markdown","metadata":{"id":"d4aLR5YCkBXU"},"source":["In the interactive interpreter, the underscore can also be used to access the result of the last executed expression:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"UYv_eapwkELr"},"outputs":[],"source":["print(2 + 3)\n","print(_ * 5)"]},{"cell_type":"markdown","metadata":{"id":"fd-twxIMkQ8r"},"source":["As you can see in this example, the underscore can be used as a shortcut to refer to the result of the last executed expression, without having to re-enter the entire expression.\n","\n","It's worth noting that using the underscore as a variable name is generally discouraged in Python, since it can be easily confused with the special uses of the character. It's best to use a more descriptive variable name to avoid confusion."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"KtxJfr72jMkO"},"outputs":[],"source":["# This list contains the numbers from 1 to 10\n","numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","\n","# We want to print out each number, but we don't need to do anything with\n","# the loop variable itself, so we use the underscore character (_) as a\n","# placeholder for the loop variable\n","for _ in numbers:\n"," print(_)"]},{"cell_type":"markdown","metadata":{"id":"ez6CVjbxjS4G"},"source":["In this example, we use a for loop to iterate over a list of numbers. We use the `_` character as the loop variable, which means that we don't need to use the loop variable itself for anything other than to indicate that the loop is running. This allows us to simply print out each number in the list without having to worry about doing anything with the loop variable itself.\n","\n","Another common use for the `_` character is as a variable name for a value that you don't intend to use. For example, you might use it when calling a function that returns multiple values, but you're only interested in using one of the values. "]},{"cell_type":"markdown","metadata":{"id":"MIwcD0yQkon6"},"source":["## Match"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"a-cd3sDrdk0p"},"outputs":[],"source":["a = int(input(\"enter your number:\\n\"))\n","match a:\n"," case 0:\n"," print(\"it's zero\")\n"," case _: # we use underscore for default case\n"," print(\"it's not a zero\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"Evx9NC7it8dD"},"outputs":[],"source":["x = int(input(\"Enter the value of x: \"))\n"," \n","# x is the variable to match\n","match x:\n"," # if x is 0\n"," case 0:\n"," print(\"x is zero\" )\n"," # case with if-condition\n"," case 1:\n"," print( \"case is one\")\n"," case _: #default case\n"," print(x)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"jY-5REuwas2a"},"outputs":[],"source":["x = int(input(\"Enter the value of x: \"))\n","# x is the variable to match\n","match x:\n"," # if x is 0\n"," case 0:\n"," print(\"x is zero\")\n"," # case with if-condition\n"," case 4:\n"," print(\"case is 4\")\n","\n"," case _ if x!=90:\n"," print(x, \"is not 90\")\n"," case _ if x!=80:\n"," print(x, \"is not 80\")\n"," case _:\n"," print(x)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"EcwpG8T3f1Pg"},"outputs":[],"source":["x = int(input(\"Enter a Number: \"))\n","# x is the variable to match\n","match x:\n"," # if x is 0\n"," case 0:\n"," print(\"x is zero\")\n","\n"," # case with if-condition\n"," case 4 if x % 2 == 0:\n"," print(\"x % 2 == 0 and case is 4\")\n","\n"," # Empty case with if-condition\n"," case _ if x < 10:\n"," print(\"x is < 10\")\n","\n"," # default case(will only be matched if the above cases were not matched)\n"," # so it is basically just an else:\n"," case _:\n"," print(x)"]},{"cell_type":"markdown","metadata":{"id":"-ioIDC9HfIXw"},"source":["## `re`"]},{"cell_type":"markdown","metadata":{"id":"7oOkW_2cmq9u"},"source":["The re module in Python is part of the standard library and provides support for regular expressions. Regular expressions are a powerful tool for matching and manipulating strings, and they can be used in a variety of ways in Python.\n","\n","Here is a simple example of how the re module can be used to search for a pattern in a string:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ZLYZgAFBmrtL"},"outputs":[],"source":["import re\n","\n","# Define a string to search\n","my_string = \"The quick brown fox jumps over the lazy dog\"\n","\n","# Use the `search` method from the `re` module to find a pattern in the string\n","result = re.search(r\"fox\", my_string)\n","\n","# Print the result\n","print(result) # Output: "]},{"cell_type":"markdown","metadata":{"id":"b1ozp1Yemv6c"},"source":["In this example, the search method from the `re` module is used to search for the pattern `\"fox\"` in the my_string variable. The `r` prefix before the string indicates that the string is a \"raw string\", which means that backslashes `(\\)` in the string are treated as literal backslashes, rather than as escape characters.\n","\n","If the search method finds a match for the pattern, it returns a Match object that contains information about the match, such as the starting and ending positions of the match within the string. If the search method does not find a match, it returns None.\n","\n","There are many other methods and functions available in the `re` module, including functions for splitting strings, replacing substrings, and more. You can learn more about the re module and how to use it in the Python documentation."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"5L-ztjjeeD6H"},"outputs":[],"source":["import re\n","\n","# Define the regular expression\n","pattern = r\"Hello\"\n","\n","# Define the string to search\n","string = \"Hello, world!\"\n","\n","# Search the string for a match to the pattern\n","match = re.match(pattern, string)\n","\n","# Check if a match was found\n","if match:\n"," print(\"Hello found!\")\n","else:\n"," print(\"Hello not found\")"]},{"cell_type":"markdown","metadata":{"id":"5EUsifRyeY15"},"source":["In this example, the `re.match()` function searches the `string` for the text \"Hello\". If it is found at the beginning of the string, it prints a message saying that \"Hello\" was found. If it is not found, it prints a message saying that \"Hello\" was not found.\n","\n","This example shows how you can use the `re.match()` function to check if a given pattern appears at the beginning of a string. You can modify the regular expression and the string to match whatever pattern you want."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"aVEj6MiIe0V8"},"outputs":[],"source":["import re\n","\n","# Match a phone number with or without a leading \"+\" sign\n","pattern = r\"\\+?\\d{3}-\\d{3}-\\d{4}\"\n","string = \"My phone number is +1-555-555-1234\"\n","match = re.match(pattern, string)\n","if match:\n"," print(f\"Phone number found: {match.group()}\")\n","else:\n"," print(\"Phone number not found\")\n","\n","# Match a date in the format \"YYYY-MM-DD\"\n","pattern = r\"\\d{4}-\\d{2}-\\d{2}\"\n","string = \"Today's date is 2022-12-14\"\n","match = re.match(pattern, string)\n","if match:\n"," print(f\"Date found: {match.group()}\")\n","else:\n"," print(\"Date not found\")\n","\n","# Match an email address\n","pattern = r\"[\\w.-]+@[\\w.-]+\"\n","string = \"My email address is myname@example.com\"\n","match = re.match(pattern, string)\n","if match:\n"," print(f\"Email address found: {match.group()}\")\n","else:\n"," print(\"Email address not found\")"]}],"metadata":{"colab":{"provenance":[]},"kernelspec":{"display_name":"Python 3 (ipykernel)","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.5"}},"nbformat":4,"nbformat_minor":0} -------------------------------------------------------------------------------- /09_New_in_Python/06_ args___kwargs .ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"toc_visible":true,"authorship_tag":"ABX9TyMYBZw+t5DAL29xpGK3KIoP"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["In Python, `*args` and `**kwargs` are special syntax used to pass a variable number of arguments to a function.\n","\n","`*args` is used to pass a non-keyworded, variable-length argument list to a function. It is often used when the number of arguments is unknown or variable. For example:"],"metadata":{"id":"9uTjhQChRbkB"}},{"cell_type":"code","execution_count":1,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"An22oxjBROWl","executionInfo":{"status":"ok","timestamp":1671552180236,"user_tz":-330,"elapsed":14,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"1da0df83-c4e2-485a-85d2-48402faf7b2e"},"outputs":[{"output_type":"stream","name":"stdout","text":["1\n","2\n","3\n","1\n","2\n","3\n","4\n","5\n"]}],"source":["def my_function(*args):\n"," for arg in args:\n"," print(arg)\n","\n","my_function(1, 2, 3) # prints 1, 2, 3\n","my_function(1, 2, 3, 4, 5) # prints 1, 2, 3, 4, 5\n"]},{"cell_type":"markdown","source":["`**kwargs` is used to pass a keyworded, variable-length argument list to a function. It is often used when the number of keyword arguments is unknown or variable. For example:"],"metadata":{"id":"9Z7Kzy2pRgaw"}},{"cell_type":"code","source":["def my_function(**kwargs):\n"," for key, value in kwargs.items():\n"," print(f\"{key} = {value}\")\n","\n","my_function(name=\"John\", age=30) # prints name = John, age = 30\n","my_function(name=\"Jane\", age=25, city=\"New York\") # prints name = Jane, age = 25, city = New York\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"80VEhv4iRhBf","executionInfo":{"status":"ok","timestamp":1671552184581,"user_tz":-330,"elapsed":5,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"66ddd737-300e-40d8-e4d4-bc69271ebc6a"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["name = John\n","age = 30\n","name = Jane\n","age = 25\n","city = New York\n"]}]},{"cell_type":"markdown","source":["Both `*args` and `**kwargs` can be used in the same function definition, but *args must come before `**kwargs`. For example:"],"metadata":{"id":"sEGu7FZCRlEO"}},{"cell_type":"code","source":["def my_function(param1, param2, *args, **kwargs):\n"," print(f\"param1 = {param1}\")\n"," print(f\"param2 = {param2}\")\n"," print(\"Args:\")\n"," for arg in args:\n"," print(arg)\n"," print(\"Keyword arguments:\")\n"," for key, value in kwargs.items():\n"," print(f\"{key} = {value}\")\n","\n","my_function(1, 2, 3, 4, 5, name=\"John\", age=30)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"KgdS0Z1yRkf2","executionInfo":{"status":"ok","timestamp":1671552282816,"user_tz":-330,"elapsed":18,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"5898da94-b54c-4c73-a71d-74f0d30dbf92"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["param1 = 1\n","param2 = 2\n","Args:\n","3\n","4\n","5\n","Keyword arguments:\n","name = John\n","age = 30\n"]}]},{"cell_type":"code","source":["def print_info(name, *args, **kwargs):\n"," print(f\"Name: {name}\")\n"," print(\"Additional information:\")\n"," for arg in args:\n"," print(arg)\n"," print(\"Keyword arguments:\")\n"," for key, value in kwargs.items():\n"," print(f\"{key} = {value}\")\n","\n","print_info(\"John\", \"Lives in New York\", \"Works as a software developer\", age=30, city=\"New York\")"],"metadata":{"id":"lqU024UZSGOn","executionInfo":{"status":"ok","timestamp":1671552335160,"user_tz":-330,"elapsed":858,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"03dce47b-d6f9-4710-d867-7799eb1c2e69","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":5,"outputs":[{"output_type":"stream","name":"stdout","text":["Name: John\n","Additional information:\n","Lives in New York\n","Works as a software developer\n","Keyword arguments:\n","age = 30\n","city = New York\n"]}]}]} -------------------------------------------------------------------------------- /09_New_in_Python/07_Python-Time-function.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyPqWG88n3GHNIr4gnaZsrlz"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":7,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"pNoGOpw9qx7T","executionInfo":{"status":"ok","timestamp":1673102631253,"user_tz":-330,"elapsed":5444,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"d6fa8f77-adec-40b8-964f-ab5c418a127c"},"outputs":[{"output_type":"stream","name":"stdout","text":["1673102625.6107056\n","time.struct_time(tm_year=2023, tm_mon=1, tm_mday=7, tm_hour=14, tm_min=43, tm_sec=45, tm_wday=5, tm_yday=7, tm_isdst=0)\n","time.struct_time(tm_year=2023, tm_mon=1, tm_mday=7, tm_hour=14, tm_min=43, tm_sec=45, tm_wday=5, tm_yday=7, tm_isdst=0)\n"]}],"source":["import time\n","\n","# Get the current time in seconds\n","current_time = time.time()\n","print(current_time)\n","\n","# Sleep for 5 seconds\n","time.sleep(5)\n","\n","# Get the current time in UTC\n","utc_time = time.gmtime(current_time)\n","print(utc_time)\n","\n","# Get the current time in the local time zone\n","local_time = time.localtime(current_time)\n","print(local_time)"]},{"cell_type":"code","source":["import time\n","import datetime\n","\n","print(time.time())\n","# 1586813438.419919\n","\n","print(time.ctime())\n","# Mon Apr 13 23:30:38 2020\n","\n","print(datetime.datetime.now())\n","# 2021-11-13 23:30:38.419951\n","\n","print(datetime.date.today())\n","# 2021-11-13"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"x16PO8yhrLp7","executionInfo":{"status":"ok","timestamp":1673102457054,"user_tz":-330,"elapsed":11,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"7fc8e7f5-655a-439a-a270-a9840ed72414"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["1673102456.1997738\n","Sat Jan 7 14:40:56 2023\n","2023-01-07 14:40:56.200827\n","2023-01-07\n"]}]},{"cell_type":"code","source":["import time\n","\n","timestamp = time.strftime('%H:%M:%S')\n","print(timestamp)\n","timestamp = time.strftime('%H')\n","print(timestamp)\n","timestamp = time.strftime('%M')\n","print(timestamp)\n","timestamp = time.strftime('%S')\n","print(timestamp)\n","# https://docs.python.org/3/library/time.html#time.strftime"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"sPahGBKDsl52","executionInfo":{"status":"ok","timestamp":1673102790849,"user_tz":-330,"elapsed":439,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"d4c3565e-9e66-4f76-815e-96042b548d61"},"execution_count":10,"outputs":[{"output_type":"stream","name":"stdout","text":["14:46:30\n","14\n","46\n","30\n"]}]}]} -------------------------------------------------------------------------------- /09_New_in_Python/08_Function_Annotations.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","metadata":{},"source":["In Python, the `->` symbol is used in function annotations, specifically to indicate the return type of a function. This is part of the type hinting system introduced in PEP 484, which allows developers to specify the expected types of variables and function return values. These annotations do not enforce type checking at runtime but can be used by third-party tools, linters, and integrated development environments (IDEs) to provide better code analysis and suggestions.\n","\n","Here's an example of how the `->` symbol is used in Python:\n","\n","### Example 1: Basic Function Annotation"]},{"cell_type":"code","execution_count":9,"metadata":{},"outputs":[],"source":["def greet(name: str) -> str:\n"," return f\"Hello, {name}!\"\n"]},{"cell_type":"markdown","metadata":{},"source":["In this example:\n","\n","- `name: str` indicates that the `name` parameter should be of type `str` (string).\n","- `-> str` indicates that the function `greet` is expected to return a `str` (string)."]},{"cell_type":"markdown","metadata":{},"source":["### Example 2: Function with Multiple Parameters"]},{"cell_type":"code","execution_count":11,"metadata":{},"outputs":[],"source":["def add(a: int, b: int) -> int:\n"," return a + b\n"]},{"cell_type":"markdown","metadata":{},"source":["In this example:\n","\n","- `a: int` and `b: int` indicate that the parameters `a` and `b` should both be of type `int` (integer).\n","- `-> int` indicates that the function `add` is expected to return an `int` (integer)."]},{"cell_type":"markdown","metadata":{},"source":["### Example 3: Function Returning a List"]},{"cell_type":"code","execution_count":12,"metadata":{},"outputs":[],"source":["def get_even_numbers(n: int) -> list[int]:\n"," return [i for i in range(n) if i % 2 == 0]\n"]},{"cell_type":"markdown","metadata":{},"source":["In this example:\n","\n","- `n: int` indicates that the parameter `n` should be of type `int`.\n","- `-> list[int]` indicates that the function `get_even_numbers` is expected to return a list of integers."]},{"cell_type":"markdown","metadata":{},"source":["### Example 4: Function with Optional Return Type"]},{"cell_type":"code","execution_count":13,"metadata":{},"outputs":[],"source":["from typing import Optional\n","\n","def find_divisor(n: int) -> Optional[int]:\n"," for i in range(2, n):\n"," if n % i == 0:\n"," return i\n"," return None\n"]},{"cell_type":"markdown","metadata":{},"source":["In this example:\n","\n","- `n: int` indicates that the parameter `n` should be of type `int`.\n","- `-> Optional[int]` indicates that the function `find_divisor` may return an `int` or `None` if no divisor is found."]},{"cell_type":"markdown","metadata":{},"source":["### Example 5: Function with Custom Type"]},{"cell_type":"code","execution_count":14,"metadata":{},"outputs":[],"source":["from typing import List, Dict\n","\n","def process_data(data: List[Dict[str, int]]) -> Dict[str, int]:\n"," result = {}\n"," for item in data:\n"," for key, value in item.items():\n"," if key in result:\n"," result[key] += value\n"," else:\n"," result[key] = value\n"," return result"]},{"cell_type":"markdown","metadata":{},"source":["In this example:\n","\n","- `data: List[Dict[str, int]]` indicates that the parameter `data` should be a list of dictionaries, where each dictionary has keys of type `str` and values of type `int`.\n","- `-> Dict[str, int]` indicates that the function `process_data` is expected to return a dictionary with keys of type `str` and values of type `int`.\n","\n","### Conclusion\n","\n","The `->` symbol in Python is a part of the function annotation syntax used for type hinting. It allows developers to specify the expected return type of a function, which can improve code readability, maintenance, and tooling support. Remember that these annotations are not enforced at runtime and are primarily used for static analysis."]}],"metadata":{"colab":{"authorship_tag":"ABX9TyPqWG88n3GHNIr4gnaZsrlz","provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.11.2"}},"nbformat":4,"nbformat_minor":0} 2 | -------------------------------------------------------------------------------- /09_New_in_Python/09_dataclasses.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "toc_visible": true 8 | }, 9 | "kernelspec": { 10 | "name": "python3", 11 | "display_name": "Python 3" 12 | }, 13 | "language_info": { 14 | "name": "python" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "markdown", 20 | "source": [ 21 | "## **`dataclasses`**" 22 | ], 23 | "metadata": { 24 | "id": "XE_IcA4YSc-F" 25 | } 26 | }, 27 | { 28 | "cell_type": "code", 29 | "source": [ 30 | "from dataclasses import dataclass\n", 31 | "\n", 32 | "@dataclass\n", 33 | "class Person:\n", 34 | " name: str\n", 35 | " age: int\n", 36 | " city: str\n", 37 | "\n", 38 | "# Creating an instance of the Person dataclass\n", 39 | "person = Person(name=\"Alice\", age=30, city=\"New York\")\n", 40 | "\n", 41 | "# Accessing the fields\n", 42 | "print(person.name) # Output: Alice\n", 43 | "print(person.age) # Output: 30\n", 44 | "print(person.city) # Output: New York" 45 | ], 46 | "metadata": { 47 | "colab": { 48 | "base_uri": "https://localhost:8080/" 49 | }, 50 | "id": "9KpkWmtTCmbd", 51 | "outputId": "07ed2ee3-e954-40f9-f2bf-425ad55b67a7" 52 | }, 53 | "execution_count": 1, 54 | "outputs": [ 55 | { 56 | "output_type": "stream", 57 | "name": "stdout", 58 | "text": [ 59 | "Alice\n", 60 | "30\n", 61 | "New York\n" 62 | ] 63 | } 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "source": [ 69 | "from dataclasses import dataclass\n", 70 | "\n", 71 | "@dataclass\n", 72 | "class Address:\n", 73 | " street: str\n", 74 | " city: str\n", 75 | " zipcode: str\n", 76 | "\n", 77 | "@dataclass\n", 78 | "class Person:\n", 79 | " name: str\n", 80 | " age: int\n", 81 | " address: Address\n", 82 | "\n", 83 | "# Creating an instance of the Address class\n", 84 | "address1 = Address(street=\"123 Main St\", city=\"New York\", zipcode=\"10001\")\n", 85 | "\n", 86 | "# Creating an instance of the Person class with the Address instance\n", 87 | "person1 = Person(name=\"Alice\", age=30, address=address1)\n", 88 | "\n", 89 | "# Accessing the nested attributes\n", 90 | "print(person1.address.city) # Output: New York" 91 | ], 92 | "metadata": { 93 | "colab": { 94 | "base_uri": "https://localhost:8080/" 95 | }, 96 | "id": "N1V7ZtvFlsGs", 97 | "outputId": "5aaa41b0-82e4-4037-f80f-3f4f8c7584c5" 98 | }, 99 | "execution_count": 2, 100 | "outputs": [ 101 | { 102 | "output_type": "stream", 103 | "name": "stdout", 104 | "text": [ 105 | "New York\n" 106 | ] 107 | } 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "source": [ 113 | "from dataclasses import dataclass, field\n", 114 | "\n", 115 | "@dataclass\n", 116 | "class Product:\n", 117 | " name: str\n", 118 | " price: float\n", 119 | " in_stock: bool = True\n", 120 | " tags: list = field(default_factory=list)\n", 121 | "\n", 122 | "# Creating an instance of the Product class\n", 123 | "product1 = Product(name=\"Laptop\", price=999.99)\n", 124 | "\n", 125 | "# Accessing the attributes\n", 126 | "print(product1.name) # Output: Laptop\n", 127 | "print(product1.in_stock) # Output: True\n", 128 | "print(product1.tags) # Output: []\n", 129 | "\n", 130 | "# Adding a tag to the product\n", 131 | "product1.tags.append(\"Electronics\")\n", 132 | "print(product1.tags)" 133 | ], 134 | "metadata": { 135 | "colab": { 136 | "base_uri": "https://localhost:8080/" 137 | }, 138 | "id": "z1312whblx0i", 139 | "outputId": "700cd896-488a-4627-d111-58d2813ab8dc" 140 | }, 141 | "execution_count": 3, 142 | "outputs": [ 143 | { 144 | "output_type": "stream", 145 | "name": "stdout", 146 | "text": [ 147 | "Laptop\n", 148 | "True\n", 149 | "[]\n", 150 | "['Electronics']\n" 151 | ] 152 | } 153 | ] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "source": [ 158 | "In this example, the `Person` class is defined as a `dataclass` with three fields: `name`, `age`, and `city`. The `dataclass` decorator automatically generates special methods like `__init__()`and `__repr__()` for the class, making it easier to work with.\n", 159 | "\n", 160 | "- The `__init__` method in Python is a **special method** used to initialize the attributes of an object when it is created. It’s often referred to as a constructor. When you create a new instance of a class, Python automatically calls the `__init__` method to set up the initial state of the object.\n", 161 | "\n", 162 | "- The `__repr__` method in Python is a **special method** used to define the string representation of an object." 163 | ], 164 | "metadata": { 165 | "id": "huCxk1dfCuey" 166 | } 167 | }, 168 | { 169 | "cell_type": "code", 170 | "source": [ 171 | "class Person:\n", 172 | " def __init__(self, name: str, age: int, city: str):\n", 173 | " self.name = name\n", 174 | " self.age = age\n", 175 | " self.city = city\n", 176 | "\n", 177 | " def __repr__(self):\n", 178 | " return f\"Person(name={self.name}, age={self.age}, city={self.city})\"\n", 179 | "\n", 180 | "# Creating an instance of the Person class\n", 181 | "person = Person(name=\"Alice\", age=30, city=\"New York\")\n", 182 | "\n", 183 | "# Accessing the fields\n", 184 | "print(person.name) # Output: Alice\n", 185 | "print(person.age) # Output: 30\n", 186 | "print(person.city) # Output: New York" 187 | ], 188 | "metadata": { 189 | "colab": { 190 | "base_uri": "https://localhost:8080/" 191 | }, 192 | "id": "GQngSHM6Dl8M", 193 | "outputId": "4605dca3-1aa3-4bed-87f6-74ae7d453501" 194 | }, 195 | "execution_count": 4, 196 | "outputs": [ 197 | { 198 | "output_type": "stream", 199 | "name": "stdout", 200 | "text": [ 201 | "Alice\n", 202 | "30\n", 203 | "New York\n" 204 | ] 205 | } 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "source": [ 211 | "If you don’t use `dataclasses`, you would typically define a class with an `__init__` method to initialize the attributes.\n", 212 | "\n", 213 | "\n", 214 | ">The `@dataclass` decorator in Python is used to automatically generate special methods for classes, such as `__init__()`, `__repr__()`, `__eq__()`, and others. **This helps reduce boilerplate code and makes it easier to create classes that are primarily used to store data.**" 215 | ], 216 | "metadata": { 217 | "id": "nrEN6XXfDrmu" 218 | } 219 | }, 220 | { 221 | "cell_type": "markdown", 222 | "source": [ 223 | "## **`typing`**\n", 224 | "\n", 225 | "\n", 226 | "The `from typing import List` statement in Python is used to import the `List` type hint from the `typing` module. This allows you to specify the type of elements that a list should contain, which can be very helpful for code readability and for tools like type checkers and IDEs to provide better support and error checking.\n", 227 | "\n", 228 | "Here’s an example of how it’s used:" 229 | ], 230 | "metadata": { 231 | "id": "rqWqyDyvTzpB" 232 | } 233 | }, 234 | { 235 | "cell_type": "code", 236 | "source": [ 237 | "from typing import List\n", 238 | "\n", 239 | "def sum_of_elements(elements: List[int]) -> int:\n", 240 | " return sum(elements)\n", 241 | "\n", 242 | "numbers = [1, 2, 3, 4, 5]\n", 243 | "print(sum_of_elements(numbers))" 244 | ], 245 | "metadata": { 246 | "colab": { 247 | "base_uri": "https://localhost:8080/" 248 | }, 249 | "id": "BFLobiRkT1-y", 250 | "outputId": "ba1d8255-440b-4156-ea80-d909490fd764" 251 | }, 252 | "execution_count": 5, 253 | "outputs": [ 254 | { 255 | "output_type": "stream", 256 | "name": "stdout", 257 | "text": [ 258 | "15\n" 259 | ] 260 | } 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "source": [ 266 | "from typing import Dict\n", 267 | "\n", 268 | "def get_student_grades() -> Dict[str, int]:\n", 269 | " return {\"Alice\": 90, \"Bob\": 85, \"Charlie\": 92}\n", 270 | "\n", 271 | "grades = get_student_grades()\n", 272 | "print(grades)" 273 | ], 274 | "metadata": { 275 | "colab": { 276 | "base_uri": "https://localhost:8080/" 277 | }, 278 | "id": "SSzIFknblN-6", 279 | "outputId": "ebe04324-e55a-4a25-96ed-8061aafb3120" 280 | }, 281 | "execution_count": 6, 282 | "outputs": [ 283 | { 284 | "output_type": "stream", 285 | "name": "stdout", 286 | "text": [ 287 | "{'Alice': 90, 'Bob': 85, 'Charlie': 92}\n" 288 | ] 289 | } 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "source": [ 295 | "from typing import Union\n", 296 | "\n", 297 | "def process_data(data: Union[int, str]) -> str:\n", 298 | " if isinstance(data, int):\n", 299 | " return f\"Processed number: {data}\"\n", 300 | " elif isinstance(data, str):\n", 301 | " return f\"Processed string: {data}\"\n", 302 | "\n", 303 | "print(process_data(10)) # Output: Processed number: 10\n", 304 | "print(process_data(\"hello\")) # Output: Processed string: hello\n" 305 | ], 306 | "metadata": { 307 | "colab": { 308 | "base_uri": "https://localhost:8080/" 309 | }, 310 | "id": "nq_kZmBWlZc6", 311 | "outputId": "37816c45-9070-497f-eb1d-ecaaa3858170" 312 | }, 313 | "execution_count": 7, 314 | "outputs": [ 315 | { 316 | "output_type": "stream", 317 | "name": "stdout", 318 | "text": [ 319 | "Processed number: 10\n", 320 | "Processed string: hello\n" 321 | ] 322 | } 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "source": [ 328 | "from typing import Optional\n", 329 | "\n", 330 | "def find_user(user_id: int) -> Optional[str]:\n", 331 | " users = {1: \"Alice\", 2: \"Bob\", 3: \"Charlie\"}\n", 332 | " return users.get(user_id)\n", 333 | "\n", 334 | "print(find_user(1)) # Output: Alice\n", 335 | "print(find_user(4)) # Output: None\n" 336 | ], 337 | "metadata": { 338 | "colab": { 339 | "base_uri": "https://localhost:8080/" 340 | }, 341 | "id": "0CfFra8rlaxr", 342 | "outputId": "c196b561-96dd-4a49-a4f5-3a8e30609135" 343 | }, 344 | "execution_count": 8, 345 | "outputs": [ 346 | { 347 | "output_type": "stream", 348 | "name": "stdout", 349 | "text": [ 350 | "Alice\n", 351 | "None\n" 352 | ] 353 | } 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "source": [ 359 | "from typing import Callable\n", 360 | "\n", 361 | "def execute_function(func: Callable[[int, int], int], a: int, b: int) -> int:\n", 362 | " return func(a, b)\n", 363 | "\n", 364 | "def add(x: int, y: int) -> int:\n", 365 | " return x + y\n", 366 | "\n", 367 | "def multiply(x: int, y: int) -> int:\n", 368 | " return x * y\n", 369 | "\n", 370 | "print(execute_function(add, 2, 3)) # Output: 5\n", 371 | "print(execute_function(multiply, 2, 3)) # Output: 6" 372 | ], 373 | "metadata": { 374 | "colab": { 375 | "base_uri": "https://localhost:8080/" 376 | }, 377 | "id": "TzSljUHPlb6h", 378 | "outputId": "b1a35987-7a64-4081-e74f-07aebad6110e" 379 | }, 380 | "execution_count": 9, 381 | "outputs": [ 382 | { 383 | "output_type": "stream", 384 | "name": "stdout", 385 | "text": [ 386 | "5\n", 387 | "6\n" 388 | ] 389 | } 390 | ] 391 | } 392 | ] 393 | } -------------------------------------------------------------------------------- /10_Python_Miscellaneous/01_List_Comprehension.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "toc_visible": true 8 | }, 9 | "kernelspec": { 10 | "name": "python3", 11 | "display_name": "Python 3" 12 | }, 13 | "language_info": { 14 | "name": "python" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "markdown", 20 | "source": [ 21 | "---\n", 22 | "\n", 23 | "

List comprehension

\n", 24 | "
\n", 25 | "\n", 26 | "---" 27 | ], 28 | "metadata": { 29 | "id": "7sIXGj0EJFas" 30 | } 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "source": [ 35 | "## **Syntax**" 36 | ], 37 | "metadata": { 38 | "id": "XwxpidjOh2Wf" 39 | } 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "source": [ 44 | "```python\n", 45 | "new_list = [expression for item in iterable]\n", 46 | "\n", 47 | "```" 48 | ], 49 | "metadata": { 50 | "id": "7VDHmZ-gJReT" 51 | } 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": 4, 56 | "metadata": { 57 | "colab": { 58 | "base_uri": "https://localhost:8080/" 59 | }, 60 | "id": "C_qi3PPPCM1Y", 61 | "outputId": "406f6284-7027-4ff1-81fa-1d9531ee3e92" 62 | }, 63 | "outputs": [ 64 | { 65 | "output_type": "stream", 66 | "name": "stdout", 67 | "text": [ 68 | "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n" 69 | ] 70 | } 71 | ], 72 | "source": [ 73 | "squares = [x**2 for x in range(1, 11)]\n", 74 | "print(squares)" 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "source": [ 80 | "```python\n", 81 | "new_list = [expression for item in iterable if condition]\n", 82 | "```" 83 | ], 84 | "metadata": { 85 | "id": "OKD_ctRRJfzU" 86 | } 87 | }, 88 | { 89 | "cell_type": "code", 90 | "source": [ 91 | "even_squares = [x**2 for x in range(1, 11) if x%2 == 0]\n", 92 | "print(even_squares)" 93 | ], 94 | "metadata": { 95 | "colab": { 96 | "base_uri": "https://localhost:8080/" 97 | }, 98 | "id": "q2SGIHgZJeQL", 99 | "outputId": "cb9b8cd3-c53e-4040-82c3-177f5078a9ab" 100 | }, 101 | "execution_count": null, 102 | "outputs": [ 103 | { 104 | "output_type": "stream", 105 | "name": "stdout", 106 | "text": [ 107 | "[4, 16, 36, 64, 100]\n" 108 | ] 109 | } 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "source": [ 115 | "## **Cartesian Product**" 116 | ], 117 | "metadata": { 118 | "id": "PnqhkEblKEet" 119 | } 120 | }, 121 | { 122 | "cell_type": "code", 123 | "source": [ 124 | "colors = ['red', 'blue', 'green']\n", 125 | "sizes = ['small', 'medium', 'large']\n", 126 | "\n", 127 | "combinations = [] # Initialize an empty list\n", 128 | "# Using nested for loops\n", 129 | "for color in colors:\n", 130 | " for size in sizes:\n", 131 | " combinations.append((color, size))\n", 132 | "\n", 133 | "# Equivalent list comprehension to generate combinations\n", 134 | "combinations_comprehension = [(color, size) for color in colors for size in sizes]\n", 135 | "\n", 136 | "print(combinations)\n", 137 | "print(combinations_comprehension)" 138 | ], 139 | "metadata": { 140 | "colab": { 141 | "base_uri": "https://localhost:8080/" 142 | }, 143 | "id": "pFbNjp2SJ9X1", 144 | "outputId": "d9aa6b7d-feb8-4e01-f350-1dc217ce3bc8" 145 | }, 146 | "execution_count": 20, 147 | "outputs": [ 148 | { 149 | "output_type": "stream", 150 | "name": "stdout", 151 | "text": [ 152 | "[('red', 'small'), ('red', 'medium'), ('red', 'large'), ('blue', 'small'), ('blue', 'medium'), ('blue', 'large'), ('green', 'small'), ('green', 'medium'), ('green', 'large')]\n", 153 | "[('red', 'small'), ('red', 'medium'), ('red', 'large'), ('blue', 'small'), ('blue', 'medium'), ('blue', 'large'), ('green', 'small'), ('green', 'medium'), ('green', 'large')]\n" 154 | ] 155 | } 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "source": [ 161 | "## **Flattening a 2D List**" 162 | ], 163 | "metadata": { 164 | "id": "laXqAZXbKF_a" 165 | } 166 | }, 167 | { 168 | "cell_type": "code", 169 | "source": [ 170 | "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", 171 | "\n", 172 | "# Using nested for loops\n", 173 | "flattened = []\n", 174 | "for row in matrix:\n", 175 | " for element in row:\n", 176 | " flattened.append(element)\n", 177 | "\n", 178 | "# Using a list comprehension\n", 179 | "flattened_comprehension = [element for row in matrix for element in row]\n", 180 | "\n", 181 | "print(flattened)\n", 182 | "print(flattened_comprehension)" 183 | ], 184 | "metadata": { 185 | "colab": { 186 | "base_uri": "https://localhost:8080/" 187 | }, 188 | "id": "nYbe4SHUKI1U", 189 | "outputId": "6106f557-8b73-4c38-f9a4-46aff5d54add" 190 | }, 191 | "execution_count": 21, 192 | "outputs": [ 193 | { 194 | "output_type": "stream", 195 | "name": "stdout", 196 | "text": [ 197 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n", 198 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" 199 | ] 200 | } 201 | ] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "source": [ 206 | "## **Filtering and Transformation**" 207 | ], 208 | "metadata": { 209 | "id": "VxxK0tmeKRZv" 210 | } 211 | }, 212 | { 213 | "cell_type": "code", 214 | "source": [ 215 | "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", 216 | "\n", 217 | "even_squares = [x**3 for x in numbers if x%3 == 0]\n", 218 | "print(even_squares)" 219 | ], 220 | "metadata": { 221 | "colab": { 222 | "base_uri": "https://localhost:8080/" 223 | }, 224 | "id": "IP6Y1WT9KSlG", 225 | "outputId": "70165cc5-a167-41ec-9fde-4747edf47c84" 226 | }, 227 | "execution_count": 6, 228 | "outputs": [ 229 | { 230 | "output_type": "stream", 231 | "name": "stdout", 232 | "text": [ 233 | "[27, 216, 729]\n" 234 | ] 235 | } 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "source": [ 241 | "## **List of Prime Numbers**" 242 | ], 243 | "metadata": { 244 | "id": "JAyIAHkUKeGU" 245 | } 246 | }, 247 | { 248 | "cell_type": "code", 249 | "source": [ 250 | "from math import sqrt\n", 251 | "\n", 252 | "def is_prime(n):\n", 253 | " if n <= 1:\n", 254 | " return False\n", 255 | " for i in range(2, int(sqrt(n)) + 1):\n", 256 | " if n % i == 0:\n", 257 | " return False\n", 258 | " return True\n", 259 | "\n", 260 | "prime_numbers = [x for x in range(2, 100) if is_prime(x)]\n", 261 | "print(prime_numbers)" 262 | ], 263 | "metadata": { 264 | "id": "T5x6HsHjKapm", 265 | "colab": { 266 | "base_uri": "https://localhost:8080/" 267 | }, 268 | "outputId": "207fc06c-a5c3-4fa4-bf35-692d673a0d97" 269 | }, 270 | "execution_count": 39, 271 | "outputs": [ 272 | { 273 | "output_type": "stream", 274 | "name": "stdout", 275 | "text": [ 276 | "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" 277 | ] 278 | } 279 | ] 280 | }, 281 | { 282 | "cell_type": "markdown", 283 | "source": [ 284 | "## **Finding Common Elements**" 285 | ], 286 | "metadata": { 287 | "id": "f5pW7ZZBKkJD" 288 | } 289 | }, 290 | { 291 | "cell_type": "code", 292 | "source": [ 293 | "list1 = [1, 2, 3, 4, 5]\n", 294 | "list2 = [3, 4, 5, 6, 7]\n", 295 | "\n", 296 | "# using nested loops\n", 297 | "comm_list = []\n", 298 | "for x in list1:\n", 299 | " if x in list2:\n", 300 | " comm_list.append(x)\n", 301 | "print(comm_list)\n", 302 | "\n", 303 | "# Using a list comprehension\n", 304 | "common_elements = [x for x in list1 if x in list2]\n", 305 | "print(common_elements)" 306 | ], 307 | "metadata": { 308 | "colab": { 309 | "base_uri": "https://localhost:8080/" 310 | }, 311 | "id": "PfZNQ_XjKlg9", 312 | "outputId": "313ba73f-0d38-4a81-daaa-372c07845229" 313 | }, 314 | "execution_count": 37, 315 | "outputs": [ 316 | { 317 | "output_type": "stream", 318 | "name": "stdout", 319 | "text": [ 320 | "[3, 4, 5]\n", 321 | "[3, 4, 5]\n" 322 | ] 323 | } 324 | ] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "source": [ 329 | "## **Transposing a Matrix**" 330 | ], 331 | "metadata": { 332 | "id": "tJB2qhCgKtiA" 333 | } 334 | }, 335 | { 336 | "cell_type": "code", 337 | "source": [ 338 | "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", 339 | "\n", 340 | "transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]\n", 341 | "print(transposed)" 342 | ], 343 | "metadata": { 344 | "colab": { 345 | "base_uri": "https://localhost:8080/" 346 | }, 347 | "id": "Pe-8VvZ5Kuj7", 348 | "outputId": "1736ed99-f513-4246-dd90-cfbb8c7e4623" 349 | }, 350 | "execution_count": null, 351 | "outputs": [ 352 | { 353 | "output_type": "stream", 354 | "name": "stdout", 355 | "text": [ 356 | "[[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n" 357 | ] 358 | } 359 | ] 360 | }, 361 | { 362 | "cell_type": "markdown", 363 | "source": [ 364 | "## **Filtering Palindromic Words**" 365 | ], 366 | "metadata": { 367 | "id": "2gCksZy1KzMT" 368 | } 369 | }, 370 | { 371 | "cell_type": "code", 372 | "source": [ 373 | "words = [\"level\", \"hello\", \"world\", \"deified\", \"python\"]\n", 374 | "\n", 375 | "palindromic_words = [word for word in words if word == word[::-1]]\n", 376 | "print(palindromic_words)" 377 | ], 378 | "metadata": { 379 | "colab": { 380 | "base_uri": "https://localhost:8080/" 381 | }, 382 | "id": "0htE1zYMK1tW", 383 | "outputId": "5bf1b0d7-ffb3-4d3d-80d7-83688dc9f4e8" 384 | }, 385 | "execution_count": null, 386 | "outputs": [ 387 | { 388 | "output_type": "stream", 389 | "name": "stdout", 390 | "text": [ 391 | "['level', 'deified']\n" 392 | ] 393 | } 394 | ] 395 | }, 396 | { 397 | "cell_type": "markdown", 398 | "source": [ 399 | "## **List of Pythagorean Triples**" 400 | ], 401 | "metadata": { 402 | "id": "QnOQxLEGK4Wl" 403 | } 404 | }, 405 | { 406 | "cell_type": "code", 407 | "source": [ 408 | "n = 10 # Maximum value for a, b, c\n", 409 | "\n", 410 | "pythagorean_triples = [(a, b, c) for a in range(1, n) for b in range(a, n) for c in range(b, n) if a**2 + b**2 == c**2]\n", 411 | "print(pythagorean_triples)" 412 | ], 413 | "metadata": { 414 | "colab": { 415 | "base_uri": "https://localhost:8080/" 416 | }, 417 | "id": "-d6CbtOKLJtk", 418 | "outputId": "1e1279bc-c972-444a-a24e-343f86022a85" 419 | }, 420 | "execution_count": null, 421 | "outputs": [ 422 | { 423 | "output_type": "stream", 424 | "name": "stdout", 425 | "text": [ 426 | "[(3, 4, 5)]\n" 427 | ] 428 | } 429 | ] 430 | } 431 | ] 432 | } -------------------------------------------------------------------------------- /10_Python_Miscellaneous/02-Objects and Data Structures Assessment Test.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","metadata":{"colab_type":"text","id":"enNfF8Fc6MYd"},"source":["# Objects and Data Structures Assessment Test"]},{"cell_type":"markdown","metadata":{"colab_type":"text","collapsed":true,"id":"T_zUjerB6MYh"},"source":["## Test your knowledge. \n","\n","** Answer the following questions **"]},{"cell_type":"markdown","metadata":{"colab_type":"text","collapsed":true,"id":"X82SeRnz6MYj"},"source":["Write a brief description of all the following Object Types and Data Structures we've learned about: "]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"eKhEkDWp6MYk"},"source":["|DATA | Types |Ordered |Allows duplicate\n","|-------------|-----------------|---------|-----------\n","|Numbers: |int,float,complex| - | -\n","| | | |\n","|*Strings*: |**Immutable** | - | -\n","| | | |\n","|Lists: |***Mutable*** |Yes |Yes\n","| | | |\n","|*Tuples*: |**Immutable** |Yes |yes\n","| | | |\n","|Dictionaries:|***Mutable*** |No |No\n","| | | |\n","|Set: |***Mutable*** |No |No\n","\n","dict & set are unorderd therefore cannot be sorted.\n","\n"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"zznjl9Nq6MYm"},"source":["## Numbers\n","\n","\n","\n","\n","\n","Write an equation that uses multiplication, division, an exponent, addition, and subtraction that is equal to 100.25.\n","\n","Hint: This is just to test your memory of the basic arithmetic commands, work backwards from 100.25"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1120,"status":"ok","timestamp":1588803868134,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"YRkjKL8Z6MYn","outputId":"66a80c4a-678e-44a7-96d1-535c8d5c31f3"},"outputs":[{"data":{"text/plain":["100.25"]},"execution_count":23,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["#Bodmas\n","((((10**2)/2)*2)+1)-.75\n"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"xkJM9QuS6MYt"},"source":["Answer these 3 questions without typing code. Then type code to check your answer.\n","\n"," What is the value of the expression 4 * (6 + 5)\n"," \n"," What is the value of the expression 4 * 6 + 5 \n"," \n"," What is the value of the expression 4 + 6 * 5 "]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1249,"status":"ok","timestamp":1588845577011,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"NIwJdMP36MYu","outputId":"9fbd23c3-a9a9-4d8a-c410-44b3acb53fa6"},"outputs":[{"name":"stdout","output_type":"stream","text":["The result for the expression is 44 29 34\n"]}],"source":["exp1 = 4 * (6 + 5)\n","exp2 = 4 * 6 + 5 \n","exp3 = 4 + 6 * 5 \n","print('The result for the expression is {r1} {r2} {r3}'.format(r1=exp1,r2=exp2,r3=exp3))"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"aOmxY0b76MYy"},"source":["What is the *type* of the result of the expression 3 + 1.5 + 4?
**Float**
\n"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"g38BC8vJ6MYz"},"source":["What would you use to find a number’s square root, as well as its square? "]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":52},"colab_type":"code","executionInfo":{"elapsed":1112,"status":"ok","timestamp":1588879387980,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"UL4StDxn6MY0","outputId":"7843b498-786b-41b5-bdf2-9eddcc199ba5"},"outputs":[{"name":"stdout","output_type":"stream","text":["2.0\n","5\n"]}],"source":["# Square root:\n","import math\n","num = math.sqrt(4)\n","print(num)\n","\n","#Another method to find SqRoot\n","a = 25**0.5\n","print(int(a))"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1371,"status":"ok","timestamp":1588845145899,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"ennz_mr-6MY5","outputId":"1c6495c7-bb16-40b4-8955-1600aa268d87"},"outputs":[{"name":"stdout","output_type":"stream","text":["4\n"]}],"source":["# Square:\n","num = 2**2\n","print(num)"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"xTVrLTe86MY9"},"source":["## Strings"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"mt1NQWlq6MY9"},"source":["Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1151,"status":"ok","timestamp":1588845711958,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"cNQhhf_n6MY-","outputId":"a7e88a69-3f06-44da-94bb-9be89d785750"},"outputs":[{"name":"stdout","output_type":"stream","text":["e\n"]}],"source":["s = 'hello'\n","# Print out 'e' using indexing\n","print(s[1])"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"n3Egw4rV6MZI"},"source":["Reverse the string 'hello' using slicing:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1120,"status":"ok","timestamp":1588845932836,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"lp4LW9t96MZJ","outputId":"2f4b955c-2857-426d-b70e-45f912d5dc08"},"outputs":[{"name":"stdout","output_type":"stream","text":["olleh\n"]}],"source":["s ='hello'\n","# Reverse the string using slicing\n","print(s[::-1])\n"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"9e2wxaOr6MZN"},"source":["Given the string hello, give two methods of producing the letter 'o' using indexing."]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":70},"colab_type":"code","executionInfo":{"elapsed":1071,"status":"ok","timestamp":1588847811597,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"KD514STS6MZN","outputId":"daeec717-ddf2-41ac-a7b5-dee2498d7ea6"},"outputs":[{"name":"stdout","output_type":"stream","text":["o\n","o\n","o\n"]}],"source":["s ='hello'\n","# Method 1:\n","print(s[-1::])\n","\n","# Method 2:\n","print(s[:-2:-1])\n","\n","# Method 3:\n","print(s[4])\n"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"UIL6uRf06MZV"},"source":["## Lists"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"_RLQm7bR6MZf"},"source":["Reassign 'hello' in this nested list to say 'goodbye' instead:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1146,"status":"ok","timestamp":1588878894052,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"qWgYTOPO6MZg","outputId":"eae0e163-b5de-43d1-9825-57dc376f04e4"},"outputs":[{"name":"stdout","output_type":"stream","text":["[1, 2, [3, 4, 'goodbye']]\n"]}],"source":["list3 = [1,2,[3,4,'hello']]\n","list3[2][2] = 'goodbye'\n","print(list3)"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"9_wKilGP6MZk"},"source":["Sort the list below:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1100,"status":"ok","timestamp":1588848504132,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"6bHiT7SJ6MZl","outputId":"95788304-5b34-435b-fe0d-6cdd0b58935e"},"outputs":[{"name":"stdout","output_type":"stream","text":["[1, 3, 4, 5, 6]\n"]}],"source":["list4 = [5,3,4,6,1]\n","list4.sort()\n","print(list4)"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"IfxgsJSY6MZq"},"source":["## Dictionaries"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"ri0f4JJF6MZq"},"source":["Using keys and indexing, grab the 'hello' from the following dictionaries:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1256,"status":"ok","timestamp":1588848847754,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"aNoGV5cQ6MZr","outputId":"e72d1954-e060-42af-e7a2-a04dca661fd9"},"outputs":[{"name":"stdout","output_type":"stream","text":["hello\n"]}],"source":["d = {'simple_key':'hello'}\n","# Grab 'hello'\n","print(d['simple_key'])"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1140,"status":"ok","timestamp":1588850693240,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"IFjkvp0k6MZv","outputId":"a588756e-979c-4dae-fece-3a3561b6c398"},"outputs":[{"name":"stdout","output_type":"stream","text":["hello\n"]}],"source":["d = {'k1':{'k2':'hello'}}\n","# Grab 'hello'\n","print(d['k1']['k2'])"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1090,"status":"ok","timestamp":1588850978963,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"3otUWWL_6MZz","outputId":"e4cd3bb6-e345-4a5a-d066-5ddc3aabbf97"},"outputs":[{"name":"stdout","output_type":"stream","text":["hello\n"]}],"source":["# Getting a little tricker\n","d = {'k1':[{'nest_key':['this is deep',['hello']]}]}\n","\n","#Grab hello\n","print(d['k1'][0]['nest_key'][1][0])"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1094,"status":"ok","timestamp":1588851167309,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"XANMc_oJ6MZ3","outputId":"0d7edb5e-448b-4bf1-ae5e-2ca6422bca64"},"outputs":[{"name":"stdout","output_type":"stream","text":["hello\n"]}],"source":["# This will be hard and annoying!\n","d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}\n","print(d['k1'][2]['k2'][1]['tough'][2][0])"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"YG5m7AzR6MZ7"},"source":["Can you sort a dictionary? Why or why not?
No becoz it unordered, So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples
"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"UmbVAc376MZ8"},"source":["## Tuples"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"CSQ5Haem6MZ8"},"source":["What is the major difference between tuples and lists?
Mutability list are mutable while tuple are Immutable
"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"6ri8VcjX6MZ9"},"source":["How do you create a tuple?
Tuples uses paranthesis:(1, 2, 3)
"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"1bxFieW76MZ9"},"source":["## Sets "]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"VzuYWUmC6MZ-"},"source":["What is unique about a set?
Unorderd & duplicate are not allowed
"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"qOfP2yOH6MZ_"},"source":["Use a set to find the unique values of the list below:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1238,"status":"ok","timestamp":1588879155049,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"DUQV_TNw6MZ_","outputId":"3fd31a30-01a6-47d1-dc0b-960da84f388d"},"outputs":[{"name":"stdout","output_type":"stream","text":["{1, 2, 33, 4, 3, 11, 22}\n"]}],"source":["list5 = [1,2,2,33,4,4,11,22,3,3,2]\n","print(set(list5))"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"mm3fZGB96MaC"},"source":["## Booleans"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"Rw_ANUKq6MaD"},"source":["For the following quiz questions, we will get a preview of comparison operators. In the table below, a=3 and b=4.\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true. (a != b) is true.
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"QXH4kOI06MaE"},"source":["What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1095,"status":"ok","timestamp":1588879190764,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"Q2usevM26MaE","outputId":"5907fff1-12e6-4c56-c1f2-f32546a4a1c3"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":5,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["# Answer before running cell\n","2 > 3 #False"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":964,"status":"ok","timestamp":1588879206753,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"z5LQ3b8Z6MaH","outputId":"f4650189-8464-4d46-f7c5-5b6a7961631c"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":6,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["# Answer before running cell\n","3 <= 2 #False"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1045,"status":"ok","timestamp":1588879217267,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"I34f-6fK6MaM","outputId":"0172a0d1-d414-4a37-d135-6297b02f5f82"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":7,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["# Answer before running cell\n","3 == 2.0 #flase"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1069,"status":"ok","timestamp":1588879229974,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"pVrqOoXz6MaQ","outputId":"5736097c-bd86-4fb7-b420-3859c86e7e83"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":8,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["# Answer before running cell\n","3.0 == 3 #True"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1124,"status":"ok","timestamp":1588879250556,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"fFTLABpr6MaT","outputId":"02d2589b-0782-4c02-f29c-139ddab0bd5b"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":9,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["# Answer before running cell\n","4**0.5 != 2 #False"]},{"cell_type":"markdown","metadata":{"colab_type":"text","id":"j0tAVqXR6MaV"},"source":["Final Question: What is the boolean output of the cell block below?"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":1160,"status":"ok","timestamp":1588879492911,"user":{"displayName":"faizy","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjOZhoo7Pw3QEureM-sfCMUcD6eyIzbktVDfFFn8Q=s64","userId":"00466318749872658969"},"user_tz":-330},"id":"Fn70I7ru6MaW","outputId":"62fd1947-29c9-49b2-ced1-4d09c7c3cba6"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":12,"metadata":{"tags":[]},"output_type":"execute_result"}],"source":["# two nested lists\n","l_one = [1,2,[3,4]]\n","l_two = [1,2,{'k1':4}]\n","\n","# True or False?\n","l_one[2][0] >= l_two[2]['k1'] #3>=4 False"]}],"metadata":{"anaconda-cloud":{},"colab":{"name":"Copy of 09-Objects and Data Structures Assessment Test.ipynb","provenance":[{"file_id":"1lwTQAsBIBizY2QAxoAzEGbcYPfFc3_2h","timestamp":1588879580014}]},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.2"}},"nbformat":4,"nbformat_minor":0} 2 | -------------------------------------------------------------------------------- /10_Python_Miscellaneous/03-Merging-two-dictionaries.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"toc_visible":true,"authorship_tag":"ABX9TyPMHvcy1QPURnjlAiE4NKr3"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["### Using the `|` Operator (Python 3.9+)\n","\n","This is the simplest and most modern way to merge dictionaries:"],"metadata":{"id":"1W_cRMNkBnst"}},{"cell_type":"code","execution_count":1,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"mj9Z9VHZBdg9","executionInfo":{"status":"ok","timestamp":1728741569535,"user_tz":-330,"elapsed":481,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"ca361139-1121-4ae2-e789-744bbf1933b2"},"outputs":[{"output_type":"stream","name":"stdout","text":["{'a': 1, 'b': 2, 'c': 3, 'd': 4}\n"]}],"source":["dict1 = {'a': 1, 'b': 2}\n","dict2 = {'c': 3, 'd': 4}\n","\n","dict1.update(dict2)\n","\n","print(dict1)"]},{"cell_type":"code","source":["dict1 = {'a': 1, 'b': 2}\n","dict2 = {'c': 3, 'd': 4}\n","\n","dict2.update(dict1)\n","\n","print(dict2)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"GtSYV_auCRLV","executionInfo":{"status":"ok","timestamp":1728741720577,"user_tz":-330,"elapsed":446,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"2ad5800f-a6c2-447b-c9a6-7a71c166c8ad"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["{'c': 3, 'd': 4, 'a': 1, 'b': 2}\n"]}]},{"cell_type":"code","source":["dict1 = {'a': 1, 'b': 2}\n","dict2 = {'b': 3, 'd': 4}\n","\n","dict1.update(dict2)\n","\n","print(dict1)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"d3BCnoavCbwc","executionInfo":{"status":"ok","timestamp":1728741758600,"user_tz":-330,"elapsed":451,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"db794622-c234-4a75-da90-1f7b9f5d98f8"},"execution_count":5,"outputs":[{"output_type":"stream","name":"stdout","text":["{'a': 1, 'b': 3, 'd': 4}\n"]}]},{"cell_type":"markdown","source":["### Using Dictionary Unpacking (`**`)\n","\n","This method works in Python 3.5 and above:"],"metadata":{"id":"rcwvGyNyBvrU"}},{"cell_type":"code","source":["dict1 = {'a': 1, 'b': 2}\n","dict2 = {'c': 3, 'd': 4}\n","\n","merged_dict = {**dict1, **dict2}\n","print(merged_dict)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"t-gmy3dlBxi2","executionInfo":{"status":"ok","timestamp":1728741591512,"user_tz":-330,"elapsed":470,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"3817176b-b17b-416f-99bf-01fc4c996395"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["{'a': 1, 'b': 2, 'c': 3, 'd': 4}\n"]}]},{"cell_type":"markdown","source":["### Using the `copy()` and `update()` Methods\n","\n","This method first copies one dictionary and then updates it with the other:"],"metadata":{"id":"UmcmwOVyB2Xk"}},{"cell_type":"code","source":["dict1 = {'a': 1, 'b': 2}\n","dict2 = {'c': 3, 'd': 4}\n","\n","merged_dict = dict1.copy()\n","merged_dict.update(dict2)\n","\n","print(merged_dict)\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"TO4C-zZeB6r2","executionInfo":{"status":"ok","timestamp":1728741627252,"user_tz":-330,"elapsed":547,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"7719e426-9c7e-4199-c7e7-4ee96195032d"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["{'a': 1, 'b': 2, 'c': 3, 'd': 4}\n"]}]}]} -------------------------------------------------------------------------------- /10_Python_Miscellaneous/04-Functions-Examples.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","metadata":{"id":"0R-pVup8vE5Z"},"source":["## **Functions Examples**\n"]},{"cell_type":"markdown","metadata":{"id":"mDdmsgrTvE5b"},"source":["#### **Example 1: Temperature Conversion**"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"lY0Yv5qzvE5c","executionInfo":{"status":"ok","timestamp":1728822351882,"user_tz":-330,"elapsed":588,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"6f37bd99-363f-41fd-c052-4f76d6d61bfc"},"outputs":[{"output_type":"stream","name":"stdout","text":["77.0\n","25.0\n"]}],"source":["def convert_temperature(temp,unit):\n"," \"\"\"This function converts temperature between Celsius and Fahrenheit\"\"\"\n"," if unit=='C':\n"," return (temp*9/5)+32 # Celsius To Fahrenheit\n"," elif unit==\"F\":\n"," return (temp-32)*5/9 # Fahrenheit to celsius\n"," else:\n"," return None\n","\n","print(convert_temperature(25,'C'))\n","print(convert_temperature(77,'F'))"]},{"cell_type":"code","source":["def celsius_to_fahrenheit(temp):\n"," return temp * 9/5 + 32\n","\n","def fahrenheit_to_celsius(temp):\n"," return (temp - 32) * 5/9\n","\n","def convert_temperature(temp, unit):\n"," \"\"\"This function converts temperature between Celsius and Fahrenheit\"\"\"\n"," conversions = {\n"," 'C': celsius_to_fahrenheit,\n"," 'F': fahrenheit_to_celsius\n"," }\n"," return conversions.get(unit, lambda x: None)(temp)\n","\n","print(convert_temperature(25, 'C'))\n","print(convert_temperature(77, 'F'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"T8qZV1xrvcFu","executionInfo":{"status":"ok","timestamp":1728822352525,"user_tz":-330,"elapsed":29,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"b95174b1-9733-4e3a-c609-de32a9a462b3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["77.0\n","25.0\n"]}]},{"cell_type":"markdown","metadata":{"id":"4Hx9lTtLvE5d"},"source":["##### **Example 2: Password Strength Checker**"]},{"cell_type":"markdown","source":["> `any()` function in Python is used to check if at least one element in an iterable (like a list, tuple, or set) is `True`"],"metadata":{"id":"CvFGQyYc5Mx5"}},{"cell_type":"code","source":["numbers = [-1, -2, -3, 0, 1, -4]\n","\n","# Check if there is any positive number in the list\n","has_positive = any(num > 0 for num in numbers)\n","\n","print(has_positive) # Output: True"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ovvT9llq5Hx2","executionInfo":{"status":"ok","timestamp":1728823373012,"user_tz":-330,"elapsed":613,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"20fc9dd6-ec96-4d8b-b28b-b5a1ec0194b3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n"]}]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"lKFoZVBIvE5e","executionInfo":{"status":"ok","timestamp":1728822352525,"user_tz":-330,"elapsed":27,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"065709ee-9200-47a1-d757-1ddb47e8dda4"},"outputs":[{"output_type":"stream","name":"stdout","text":["False\n","True\n"]}],"source":["def is_strong_password(password):\n"," \"\"\"This function checks if the password is strong or not\"\"\"\n"," if len(password)<8:\n"," return False\n"," if not any(char.isdigit() for char in password):\n"," return False\n"," if not any(char.islower() for char in password):\n"," return False\n"," if not any(char.isupper() for char in password):\n"," return False\n"," if not any(char in '!@#$%^&*()_+' for char in password):\n"," return False\n"," return True\n","\n","## calling the function\n","print(is_strong_password(\"WeakPwd\"))\n","print(is_strong_password(\"Str0ngPwd!\"))"]},{"cell_type":"markdown","source":["**Using Regular Expression**"],"metadata":{"id":"1BQXUfmgwKpi"}},{"cell_type":"code","source":["import re\n","\n","def is_strong_password(password):\n"," \"\"\"This function checks if the password is strong or not\"\"\"\n"," if len(password) < 8:\n"," return False\n"," if not re.search(r'\\d', password):\n"," return False\n"," if not re.search(r'[a-z]', password):\n"," return False\n"," if not re.search(r'[A-Z]', password):\n"," return False\n"," if not re.search(r'[!@#$%^&*()_+]', password):\n"," return False\n"," return True\n","\n","# Calling the function\n","print(is_strong_password(\"WeakPwd\"))\n","print(is_strong_password(\"Str0ngPwd!\"))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"WdKLNGJdvsYc","executionInfo":{"status":"ok","timestamp":1728822352525,"user_tz":-330,"elapsed":24,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"9a4407e7-f381-416c-e0b9-da1aeee05bac"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["False\n","True\n"]}]},{"cell_type":"markdown","metadata":{"id":"-j_KYMIkvE5f"},"source":["##### **Example 3: Calculate the Total Cost Of Items In a Shopping Cart**"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"5pQ0NhqtvE5f","executionInfo":{"status":"ok","timestamp":1728822352525,"user_tz":-330,"elapsed":23,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"41c19120-a789-46e5-c6b6-38c7ed479a2f"},"outputs":[{"output_type":"stream","name":"stdout","text":["5.8999999999999995\n"]}],"source":["def calculate_total_cost(cart):\n"," total_cost=0\n"," for item in cart:\n"," total_cost+=item['price']* item['quantity']\n","\n"," return total_cost\n","\n","\n","## Example cart data\n","\n","cart=[\n"," {'name':'Apple','price':0.5,'quantity':4},\n"," {'name':'Banana','price':0.3,'quantity':6},\n"," {'name':'Orange','price':0.7,'quantity':3}\n","\n","]\n","\n","## calling the function\n","total_cost=calculate_total_cost(cart)\n","print(total_cost)"]},{"cell_type":"markdown","metadata":{"id":"jZhUwiYSvE5g"},"source":["##### **Example 4: Check IF a String Is Palindrome**"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"jkTMHDjwvE5h","executionInfo":{"status":"ok","timestamp":1728822352525,"user_tz":-330,"elapsed":22,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"1b3fcde5-3ed5-4a62-fea2-c7bca70e66fd"},"outputs":[{"output_type":"stream","name":"stdout","text":["True\n","False\n"]}],"source":["def is_palindrome(s):\n"," s=s.lower().replace(\" \",\"\")\n"," return s==s[::-1]\n","\n","print(is_palindrome(\"A man a plan a canal Panama\"))\n","print(is_palindrome(\"Hello\"))"]},{"cell_type":"markdown","metadata":{"id":"kkDrefwtvE5h"},"source":["##### **Example 5: Calculate the factorials of a number using recursion**"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"VYcvucJgvE5i","executionInfo":{"status":"ok","timestamp":1728822352525,"user_tz":-330,"elapsed":20,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"77d952cc-dce8-46b0-bd83-669744bda15c"},"outputs":[{"output_type":"stream","name":"stdout","text":["720\n"]}],"source":["def factorial(n):\n"," if n==0:\n"," return 1\n"," else:\n"," return n * factorial(n-1)\n","\n","print(factorial(6))"]},{"cell_type":"markdown","metadata":{"id":"u34VNjtCvE5i"},"source":["##### **Example 6: A Function To Read A File and count the frequency of each word**"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"gApkNgWuvE5j","executionInfo":{"status":"ok","timestamp":1728822558557,"user_tz":-330,"elapsed":595,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"dfd81cac-05b8-4f16-e4f3-ca4d3631a978"},"outputs":[{"output_type":"stream","name":"stdout","text":["{'this': 2, 'is': 3, 'a': 1, 'test': 3, 'simple': 2, 'good': 1}\n"]}],"source":["# Create a sample text file\n","sample_text = \"\"\"This is a test. This test is simple. Simple test is good.\"\"\"\n","\n","with open('sample.txt', 'w') as file:\n"," file.write(sample_text)\n","\n","# Define the function\n","def count_word_frequency(file_path):\n"," word_count = {}\n"," with open(file_path, 'r') as file:\n"," for line in file:\n"," words = line.split()\n"," for word in words:\n"," word = word.lower().strip('.,!?;:\"\\'')\n"," word_count[word] = word_count.get(word, 0) + 1\n"," return word_count\n","\n","# Use the created file\n","filepath = 'sample.txt'\n","word_frequency = count_word_frequency(filepath)\n","print(word_frequency)"]},{"cell_type":"markdown","metadata":{"id":"snYe8QNyvE5j"},"source":["##### **Example 7: Validate Email Address**"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Y0yZmub4vE5j","executionInfo":{"status":"ok","timestamp":1728822565621,"user_tz":-330,"elapsed":583,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"90d35379-9dbe-47df-a029-e6071aa8b012"},"outputs":[{"output_type":"stream","name":"stdout","text":["True\n","False\n"]}],"source":["import re\n","\n","# Email validation function\n","def is_valid_email(email):\n"," \"\"\"This function checks if the email is valid.\"\"\"\n"," pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'\n"," return re.match(pattern, email) is not None\n","\n","# Calling the function\n","print(is_valid_email(\"test@example.com\")) # Output: True\n","print(is_valid_email(\"invalid-email\")) # Output: False\n"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.12.0"},"colab":{"provenance":[],"toc_visible":true}},"nbformat":4,"nbformat_minor":0} -------------------------------------------------------------------------------- /10_Python_Miscellaneous/06_Python_OS Module_.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"toc_visible":true,"authorship_tag":"ABX9TyOJV7j0B1mz5ccYTo8hQD5F"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["![Python_os_img](https://th.bing.com/th/id/OIP.qbcZ4xObe_7Zs-LnIjYn1AHaDF?rs=1&pid=ImgDetMain)"],"metadata":{"id":"oJF525hO7Jm3"}},{"cell_type":"markdown","source":["The Python `os` module provides a way to interact with the operating system. It allows you to perform various OS-level tasks, like file and directory manipulation, environment variable management, and process-related operations.\n","\n","\n","## 1. **File and Directory Manipulation**\n"],"metadata":{"id":"21kMh8UX7cJB"}},{"cell_type":"markdown","source":["1. **`os.getcwd()`** - Get the current working directory.\n","2. **`os.chdir(path)`** - Change the current working directory.\n","3. **`os.listdir(path)`** - List files and directories in a given directory.\n","4. **`os.mkdir(path)`** - Create a new directory.\n","5. **`os.makedirs(path)`** - Create directories, including intermediate ones.\n","6. **`os.remove(path)`** - Remove a file.\n","7. **`os.rmdir(path)`** - Remove an empty directory.\n","8. **`os.rename(src, dst)`** - Rename a file or directory."],"metadata":{"id":"FtOJ9rPlY20s"}},{"cell_type":"code","source":["import os"],"metadata":{"id":"cZ2fHb568kxl","executionInfo":{"status":"ok","timestamp":1732874800150,"user_tz":-330,"elapsed":1776,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}}},"execution_count":1,"outputs":[]},{"cell_type":"code","source":["# Get current working directory\n","print(\"Current directory:\", os.getcwd())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"KZzaCi_f8mBn","executionInfo":{"status":"ok","timestamp":1732874800151,"user_tz":-330,"elapsed":40,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"1da49dcd-441e-4b26-a58a-0abe36ddcbf0"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["Current directory: /content\n"]}]},{"cell_type":"code","source":["# Change to a new directory (for demonstration, let's use '/content' in Google Colab)\n","os.chdir('/content/sample_data/')\n","print(\"Changed directory to:\", os.getcwd())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"BQ5VuXhv8omu","executionInfo":{"status":"ok","timestamp":1732874800151,"user_tz":-330,"elapsed":30,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"8e0807a1-bf6f-4fb8-fff6-c4a28fb6ced8"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["Changed directory to: /content/sample_data\n"]}]},{"cell_type":"code","source":["# Create a new directory\n","os.mkdir(\"sample_dir\")\n","print(\"Directory 'sample_dir' created.\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"IPjA0noY87ik","executionInfo":{"status":"ok","timestamp":1732874800151,"user_tz":-330,"elapsed":29,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"98e6346c-241b-40a6-818f-54ae47ee0766"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["Directory 'sample_dir' created.\n"]}]},{"cell_type":"code","source":["# List contents of the current directory\n","print(\"Directory contents:\", os.listdir('.'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Q1Nm8tAL88ue","executionInfo":{"status":"ok","timestamp":1732874800151,"user_tz":-330,"elapsed":28,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"3f6ec554-86ed-467b-df2a-cc684abf8b7a"},"execution_count":5,"outputs":[{"output_type":"stream","name":"stdout","text":["Directory contents: ['README.md', 'anscombe.json', 'sample_dir', 'california_housing_train.csv', 'california_housing_test.csv', 'mnist_train_small.csv', 'mnist_test.csv']\n"]}]},{"cell_type":"code","source":["# Rename the directory\n","os.rename(\"sample_dir\", \"renamed_dir\")\n","print(\"Directory renamed to 'renamed_dir'.\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"fFEhXzlp89_k","executionInfo":{"status":"ok","timestamp":1732874800151,"user_tz":-330,"elapsed":26,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"53984072-41f1-4865-ee54-61f314e11eff"},"execution_count":6,"outputs":[{"output_type":"stream","name":"stdout","text":["Directory renamed to 'renamed_dir'.\n"]}]},{"cell_type":"code","execution_count":7,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"hYOiADzI6rGU","executionInfo":{"status":"ok","timestamp":1732874800151,"user_tz":-330,"elapsed":25,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"25fc1e26-e21f-44b3-f4dc-ff16c3db6d55"},"outputs":[{"output_type":"stream","name":"stdout","text":["Directory 'renamed_dir' removed.\n"]}],"source":["# Remove the directory\n","os.rmdir(\"renamed_dir\")\n","print(\"Directory 'renamed_dir' removed.\")"]},{"cell_type":"markdown","source":["## 2. **Environment Variable Management**\n","\n"],"metadata":{"id":"Uj_FHEh_7mR1"}},{"cell_type":"markdown","source":["1. **`os.getenv('VAR_NAME')`** - Get an environment variable.\n","2. **`os.putenv('VAR_NAME', 'value')`** - Set an environment variable.\n","3. **`os.environ['VAR_NAME']`** - Another way to set/get environment variables."],"metadata":{"id":"9mNLYjqMY-ua"}},{"cell_type":"code","source":["# Set an environment variable\n","os.environ['MY_VAR'] = 'Hello Colab'\n","print(\"Environment variable 'MY_VAR' set.\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"69_e4plEBQ9S","executionInfo":{"status":"ok","timestamp":1732874851753,"user_tz":-330,"elapsed":1688,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"e833f4e8-b5d3-4876-a33b-b25ad0956259"},"execution_count":16,"outputs":[{"output_type":"stream","name":"stdout","text":["Environment variable 'MY_VAR' set.\n"]}]},{"cell_type":"code","source":["# Get an environment variable\n","print(\"MY_VAR:\", os.getenv('MY_VAR'))\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"txbUAcAeBSra","executionInfo":{"status":"ok","timestamp":1732874851753,"user_tz":-330,"elapsed":10,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"8133ed54-80ea-4d98-ade7-558facfc658e"},"execution_count":17,"outputs":[{"output_type":"stream","name":"stdout","text":["MY_VAR: Hello Colab\n"]}]},{"cell_type":"code","source":["# Modify the environment variable\n","os.environ['MY_VAR'] = 'Hello Python'\n","print(\"MY_VAR modified to:\", os.getenv('MY_VAR'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Oz5PyorJBUCy","executionInfo":{"status":"ok","timestamp":1732874851753,"user_tz":-330,"elapsed":9,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"146266cb-4c66-41ce-af62-c5d98ba787f3"},"execution_count":18,"outputs":[{"output_type":"stream","name":"stdout","text":["MY_VAR modified to: Hello Python\n"]}]},{"cell_type":"code","source":["# Delete an environment variable (method: unset it)\n","del os.environ['MY_VAR']\n","print(\"MY_VAR deleted.\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"GtpRFgPA7q42","executionInfo":{"status":"ok","timestamp":1732874851754,"user_tz":-330,"elapsed":10,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"dfbc3ff3-e7b0-4ba0-a80a-7de23aee6736"},"execution_count":19,"outputs":[{"output_type":"stream","name":"stdout","text":["MY_VAR deleted.\n"]}]},{"cell_type":"markdown","source":["## 3. **Path Manipulation**\n","\n"],"metadata":{"id":"Gp_2ZQ7m7tD3"}},{"cell_type":"markdown","source":["1. **`os.path.join(path, *paths)`** - Join one or more path components.\n","2. **`os.path.exists(path)`** - Check if a path exists.\n","3. **`os.path.isdir(path)`** - Check if a path is a directory.\n","4. **`os.path.isfile(path)`** - Check if a path is a file.\n","5. **`os.path.abspath(path)`** - Get the absolute path."],"metadata":{"id":"uhZXThyuZB3c"}},{"cell_type":"code","source":["import os\n","\n","# Join paths\n","full_path = os.path.join('/content', 'sample_file.txt')\n","print(\"Joined path:\", full_path)\n","\n","# Check if path exists\n","print(\"Does the path exist?\", os.path.exists(full_path))\n","\n","# Check if path is directory\n","print(\"Is it a directory?\", os.path.isdir('/content'))\n","\n","# Check if path is file\n","print(\"Is it a file?\", os.path.isfile('/content/sample_file.txt'))\n","\n","# Get absolute path\n","print(\"Absolute path of current directory:\", os.path.abspath('.'))"],"metadata":{"id":"IH20HqGK7vKE","executionInfo":{"status":"ok","timestamp":1732874800152,"user_tz":-330,"elapsed":15,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"b793bcd3-8a8c-409d-e663-a8e4a4481b0f","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":12,"outputs":[{"output_type":"stream","name":"stdout","text":["Joined path: /content/sample_file.txt\n","Does the path exist? False\n","Is it a directory? True\n","Is it a file? False\n","Absolute path of current directory: /content/sample_data\n"]}]},{"cell_type":"markdown","source":["## 4. **Executing System Commands**\n","\n"],"metadata":{"id":"mKZyhsuQ7zUt"}},{"cell_type":"markdown","source":["1. **`os.system(command)`** - Run a shell command (useful for running commands directly from Python)."],"metadata":{"id":"JwBo-Tn5ZFfV"}},{"cell_type":"code","source":["import os\n","\n","# Execute a shell command to list files in the current directory\n","os.system(\"ls\")\n"],"metadata":{"id":"Abw58Tci7yMG","executionInfo":{"status":"ok","timestamp":1732874800152,"user_tz":-330,"elapsed":14,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"5432f52a-abbd-43f8-95f6-8a76ec0cf757","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":13,"outputs":[{"output_type":"execute_result","data":{"text/plain":["0"]},"metadata":{},"execution_count":13}]},{"cell_type":"markdown","source":["> **Note**: `os.system` is useful for executing shell commands but for complex tasks, you may want to use Python’s `subprocess` module instead."],"metadata":{"id":"O85Vw88w73WN"}},{"cell_type":"markdown","source":[],"metadata":{"id":"eKUsk89mZE0V"}},{"cell_type":"markdown","source":["## 5. **Working with Processes**\n","\n"],"metadata":{"id":"nFprpL5T77S9"}},{"cell_type":"markdown","source":["1. **`os.getpid()`** - Get the current process ID.\n","2. **`os.getppid()`** - Get the parent process ID.\n","3. **`os.fork()`** - Fork a process (Unix-based systems only)."],"metadata":{"id":"ibODXydkZKHm"}},{"cell_type":"code","source":["import os\n","\n","# Get current process ID\n","print(\"Current process ID:\", os.getpid())\n","\n","# Get parent process ID\n","print(\"Parent process ID:\", os.getppid())"],"metadata":{"id":"HqfVnjsI79tv","executionInfo":{"status":"ok","timestamp":1732874800152,"user_tz":-330,"elapsed":12,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"fa26e9a2-747e-4c12-9810-92e7e4d7dab1","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":14,"outputs":[{"output_type":"stream","name":"stdout","text":["Current process ID: 324\n","Parent process ID: 90\n"]}]},{"cell_type":"markdown","source":["> **Note**: The `os.fork()` method only works on Unix-based systems like Linux. It creates a child process and is mainly used for low-level process management."],"metadata":{"id":"CimKeYnB7_i-"}},{"cell_type":"markdown","source":["## 6. **Handling File Permissions**\n","\n"],"metadata":{"id":"tLPPDi078DFF"}},{"cell_type":"markdown","source":["1. **`os.chmod(path, mode)`** - Change the mode of a path (file or directory).\n","2. **`os.access(path, mode)`** - Check permission on a path."],"metadata":{"id":"QbshMk8aZN0B"}},{"cell_type":"code","source":["import os\n","import stat\n","\n","# Create a file\n","with open(\"sample_file.txt\", \"w\") as f:\n"," f.write(\"Sample content\")\n","\n","# Check if the file exists and change permissions\n","if os.path.exists(\"sample_file.txt\"):\n"," os.chmod(\"sample_file.txt\", stat.S_IREAD) # Read-only permission\n"," print(\"File 'sample_file.txt' set to read-only.\")\n","\n"," # Check if the file is readable and writable\n"," print(\"Is readable?\", os.access(\"sample_file.txt\", os.R_OK))\n"," print(\"Is writable?\", os.access(\"sample_file.txt\", os.W_OK))\n","\n"," # Clean up by removing the file\n"," os.remove(\"sample_file.txt\")\n"," print(\"File 'sample_file.txt' removed.\")"],"metadata":{"id":"tW9LRbNB8FCE","executionInfo":{"status":"ok","timestamp":1732874800152,"user_tz":-330,"elapsed":12,"user":{"displayName":"Mohd Faizy","userId":"00466318749872658969"}},"outputId":"0550bb05-3280-4689-98e4-02f297711324","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":15,"outputs":[{"output_type":"stream","name":"stdout","text":["File 'sample_file.txt' set to read-only.\n","Is readable? True\n","Is writable? True\n","File 'sample_file.txt' removed.\n"]}]}]} -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/01_beginners_python_cheat_sheet_pcc.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/01_beginners_python_cheat_sheet_pcc.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/02_beginners_python_cheat_sheet_pcc_lists.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/02_beginners_python_cheat_sheet_pcc_lists.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/03_beginners_python_cheat_sheet_pcc_dictionaries.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/03_beginners_python_cheat_sheet_pcc_dictionaries.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/04_beginners_python_cheat_sheet_pcc_if_while.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/04_beginners_python_cheat_sheet_pcc_if_while.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/05_beginners_python_cheat_sheet_pcc_functions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/05_beginners_python_cheat_sheet_pcc_functions.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/06_beginners_python_cheat_sheet_pcc_classes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/06_beginners_python_cheat_sheet_pcc_classes.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/07_beginners_python_cheat_sheet_pcc_files_exceptions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/07_beginners_python_cheat_sheet_pcc_files_exceptions.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/01_python Crash Course - Cheat sheet/08_beginners_python_cheat_sheet_pcc_django.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/01_python Crash Course - Cheat sheet/08_beginners_python_cheat_sheet_pcc_django.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/01_PythonForDataScience_Python.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/01_PythonForDataScience_Python.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/02_PythonForDataScience_Pandas-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/02_PythonForDataScience_Pandas-1.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/03_PythonForDataScience_Pandas-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/03_PythonForDataScience_Pandas-2.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/04_PythonForDataScience_Numpy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/04_PythonForDataScience_Numpy.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/05_PythonForDataScience_Matplotlib.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/05_PythonForDataScience_Matplotlib.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/06_PythonForDataScience_Bokeh.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/06_PythonForDataScience_Bokeh.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/07_PythonForDataScience_Seaborn.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/07_PythonForDataScience_Seaborn.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/08_PythonForDataScience_ImportingData.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/08_PythonForDataScience_ImportingData.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/09-PythonForDataScience_JupyterNoteBook.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/09-PythonForDataScience_JupyterNoteBook.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/10_PythonForDataScience_LinearAlzebra.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/10_PythonForDataScience_LinearAlzebra.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/11_PythonForDataScience_Sckit-Learn.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/11_PythonForDataScience_Sckit-Learn.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/02_Python For DataScience/12_PythonForDataScience_Keras.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/02_Python For DataScience/12_PythonForDataScience_Keras.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/Python 3 Cheat Sheet (credits - Laurent Pointal).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/Python 3 Cheat Sheet (credits - Laurent Pointal).pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/Python DataQuest.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/Python DataQuest.jpg -------------------------------------------------------------------------------- /_Python_Cheatsheets/Python Quick Guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/Python Quick Guide.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/PythonCheatSheet-keywords.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/PythonCheatSheet-keywords.pdf -------------------------------------------------------------------------------- /_Python_Cheatsheets/Python_Intellipaat.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_Python_Cheatsheets/Python_Intellipaat.pdf -------------------------------------------------------------------------------- /_img/Python_CS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_img/Python_CS.png -------------------------------------------------------------------------------- /_img/carClass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_img/carClass.png -------------------------------------------------------------------------------- /_img/py_hw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_img/py_hw.png -------------------------------------------------------------------------------- /_img/train_berth_bp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohd-faizy/learn_python/e52799b6c3dee2810adb9154e5abc8f4c6c6ee06/_img/train_berth_bp.jpg --------------------------------------------------------------------------------