├── .gitignore ├── Module_2_Python_programming_Fundamentals ├── Lab_03_collections_list_tuple_dictionary.ipynb ├── images │ ├── Keywords_list_python.PNG │ ├── Keywords_list_python_docs_org.PNG │ └── built_in_function.PNG ├── lab_M01_001_print_input.ipynb ├── lab_M01_002_practice_problesm.ipynb └── lab_M01_003_reserved_keyword_inbuilt_function.ipynb ├── Module_3_Control_Structure ├── lab_06_if_else_for.ipynb ├── lab_07_while_loop_break_continue_pass.ipynb └── lab_08_for_loop.ipynb ├── Module_4_Collections ├── lab_08_list.ipynb ├── lab_09_dictionary.ipynb ├── lab_09_sets.ipynb └── lab_09_tuple.ipynb ├── Module_5_Strings_and_Regular_Expressions ├── lab_10_mutable_vs_immutable.ipynb ├── lab_10_string_practice.ipynb ├── lab_10_strings.ipynb └── lab_11_regular_expression.ipynb ├── Module_6_Functions_and_Files ├── Module_6_Files.pptx ├── Module_6_Function.pptx ├── VIT_BCSE101E_Functions.ipynb ├── file_read_1.py ├── file_read_2.py ├── file_read_write_demonstration.ipynb ├── images │ ├── factorial_function_recursive_call_stack.drawio.png │ └── fibonacci_recursion_call_stack.drawio.png ├── lab_11_2_function.ipynb ├── lab_11_functions_practice.ipynb └── sample.txt ├── Module_7_Modules_and_Packages ├── Pandas.ipynb └── numpy.ipynb └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Module_2_Python_programming_Fundamentals/Lab_03_collections_list_tuple_dictionary.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","id":"3de93112","metadata":{"id":"3de93112"},"source":["# Collections :- list, tuple, dictionary, set"]},{"cell_type":"markdown","id":"8726fb17","metadata":{"id":"8726fb17"},"source":["## List\n","- List is collection of heterogeneous items\n","- List size can be changed dynamically"]},{"cell_type":"code","execution_count":1,"id":"0af0cf2c","metadata":{"id":"0af0cf2c","executionInfo":{"status":"ok","timestamp":1693566888164,"user_tz":-330,"elapsed":9,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[],"source":["# declaration of a list\n","my_list = [1,7,58,24, 'BCSE101E', 'NLP', 99.8,'Windows']"]},{"cell_type":"code","execution_count":2,"id":"0702d2ca","metadata":{"id":"0702d2ca","outputId":"e85fe1b6-4046-4b3d-8099-ad0090623641","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1693566888165,"user_tz":-330,"elapsed":8,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["58\n","7\n","NLP\n"]}],"source":["# accessing elements of list - list index starts from 0\n","print(my_list[2])\n","print(my_list[1])\n","print(my_list[5])"]},{"cell_type":"code","execution_count":3,"id":"d69fe42a","metadata":{"id":"d69fe42a","outputId":"94197ca4-6b84-406b-d75b-4cb93d526fa5","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1693566913108,"user_tz":-330,"elapsed":485,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["before re-assigning [1, 7, 58, 24, 'BCSE101E', 'NLP', 99.8, 'Windows']\n"," After re-assigning [1, 7, 58, 'new_item', 'BCSE101E', 'NLP', 99.8, 'Windows']\n"]}],"source":["# re-assigning an list index\n","print('before re-assigning', my_list)\n","my_list[3] = 'new_item'\n","print(' After re-assigning' , my_list)"]},{"cell_type":"markdown","source":[],"metadata":{"id":"pMWn2DiPdGmV"},"id":"pMWn2DiPdGmV"},{"cell_type":"code","execution_count":4,"id":"324fce0d","metadata":{"id":"324fce0d","outputId":"76a35377-2978-47b4-809c-59a3eccb2e5d","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1693567227212,"user_tz":-330,"elapsed":450,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[58, 'new_item', 'BCSE101E', 'NLP', 99.8]\n","[58, 'BCSE101E', 99.8]\n"]}],"source":["# slicing and striding over list\n","print(my_list[2:7])\n","print(my_list[2:7:2])"]},{"cell_type":"code","execution_count":5,"id":"634033c5","metadata":{"id":"634033c5","outputId":"32ccf4c3-81c2-46a6-8bef-4795c7bb4f10","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1693567277094,"user_tz":-330,"elapsed":439,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Windows\n","99.8\n","NLP\n","new_item\n"]}],"source":["# List can also be accessed with negative indxing\n","print(my_list[-1])\n","print(my_list[-2])\n","print(my_list[-3])\n","print(my_list[-5])"]},{"cell_type":"code","source":["my_list.append(199)\n","print(my_list[-1])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vRiDsUZbiAgn","executionInfo":{"status":"ok","timestamp":1693568248827,"user_tz":-330,"elapsed":417,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"9c56a96c-06a9-4fdd-a89f-f02d7510a027"},"id":"vRiDsUZbiAgn","execution_count":6,"outputs":[{"output_type":"stream","name":"stdout","text":["199\n"]}]},{"cell_type":"code","source":["print(my_list[:4])\n","my_list.insert(2, 96)\n","print(my_list[:4])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"EG37fReLjE63","executionInfo":{"status":"ok","timestamp":1693568589085,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"56a0f20c-607e-456b-81df-4b292582f4ca"},"id":"EG37fReLjE63","execution_count":9,"outputs":[{"output_type":"stream","name":"stdout","text":["[1, 7, 58, 'new_item']\n","[1, 7, 96, 58]\n"]}]},{"cell_type":"markdown","id":"5bc352ca","metadata":{"id":"5bc352ca"},"source":["## Tuples\n","- tuple is also a collection of heteregenous elements"]},{"cell_type":"code","execution_count":null,"id":"4618c054","metadata":{"id":"4618c054","outputId":"428efa91-6777-4524-ce1d-418c3262c2f4"},"outputs":[{"name":"stdout","output_type":"stream","text":["(1, 'ram', 67, 3.14, 'BCSE101E')\n"]}],"source":["#tuple declaration\n","my_tup = (1,'ram', 67, 3.14, 'BCSE101E')\n","print(my_tup)\n"]},{"cell_type":"code","execution_count":null,"id":"8ec066b8","metadata":{"id":"8ec066b8","outputId":"73a07865-dec9-4ffc-fcaa-d43a4675cbcc"},"outputs":[{"name":"stdout","output_type":"stream","text":["ram\n","BCSE101E\n","1\n"]}],"source":["# Accessing elements of tuple - tuple indexing start from zero (0)\n","print(my_tup[1])\n","print(my_tup[4])\n","print(my_tup[0])"]},{"cell_type":"code","source":["list_loc = [ (2,3) , (4,5), (7,13)]\n","print(list_loc[1][0])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Ny9PnXRVlshe","executionInfo":{"status":"ok","timestamp":1693570381882,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b5c61f8d-049f-49ff-f030-51959de6c651"},"id":"Ny9PnXRVlshe","execution_count":17,"outputs":[{"output_type":"stream","name":"stdout","text":["4\n"]}]},{"cell_type":"markdown","id":"4295989a","metadata":{"id":"4295989a"},"source":["## Dictionary\n","- a key-value pair"]},{"cell_type":"code","execution_count":13,"id":"97281ca9","metadata":{"id":"97281ca9","executionInfo":{"status":"ok","timestamp":1693570094269,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[],"source":["d= {1: 'ram', 2 :'shyam', 7: 'Mohan'}"]},{"cell_type":"code","execution_count":null,"id":"cce13566","metadata":{"id":"cce13566","outputId":"41c44151-da33-40b4-d0ec-84c0e7831efd"},"outputs":[{"name":"stdout","output_type":"stream","text":["{1: 'ram', 2: 'shyam', 7: 'Mohan'}\n"]}],"source":["print(d)"]},{"cell_type":"code","source":["print(d[1])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"x1L9q2GFpOeF","executionInfo":{"status":"ok","timestamp":1693570149937,"user_tz":-330,"elapsed":684,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"0736e1d1-0d24-4fd6-e6b8-0f5889b004c4"},"id":"x1L9q2GFpOeF","execution_count":16,"outputs":[{"output_type":"stream","name":"stdout","text":["ram\n"]}]},{"cell_type":"code","source":["print(d[7])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"rA3GQCkHpQcl","executionInfo":{"status":"ok","timestamp":1693570119298,"user_tz":-330,"elapsed":458,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b867d5e6-5db9-4feb-89c9-b6c24bb87808"},"id":"rA3GQCkHpQcl","execution_count":15,"outputs":[{"output_type":"stream","name":"stdout","text":["Mohan\n"]}]},{"cell_type":"code","execution_count":null,"id":"3a9daea5","metadata":{"id":"3a9daea5","outputId":"813720ef-81ad-4c4c-b258-25dd95150bfd"},"outputs":[{"name":"stdout","output_type":"stream","text":["dict_keys([1, 2, 7])\n"]}],"source":["print(d.keys())"]},{"cell_type":"code","execution_count":null,"id":"6d61911c","metadata":{"id":"6d61911c","outputId":"7614c4b0-15e3-4e06-d0b9-47548e320e6d"},"outputs":[{"name":"stdout","output_type":"stream","text":["dict_values(['ram', 'shyam', 'Mohan'])\n"]}],"source":["print(d.values())"]},{"cell_type":"code","execution_count":null,"id":"9b6c13d7","metadata":{"id":"9b6c13d7","outputId":"c49d1fe8-ae7f-4170-8edb-49b2fead71a6"},"outputs":[{"name":"stdout","output_type":"stream","text":["dict_items([(1, 'ram'), (2, 'shyam'), (7, 'Mohan')])\n"]}],"source":["print(d.items())"]},{"cell_type":"code","execution_count":null,"id":"20528258","metadata":{"id":"20528258","outputId":"c181d916-702a-4f6b-a0ce-4b2663f49702"},"outputs":[{"name":"stdout","output_type":"stream","text":["dict_keys([1, 2, 7])\n","\n"]}],"source":["keys_list = d.keys()\n","print(keys_list)\n","print(type(keys_list))"]},{"cell_type":"code","execution_count":null,"id":"040d0a5f","metadata":{"id":"040d0a5f","outputId":"6718fe5f-d859-44ea-979e-1c5977bf18df"},"outputs":[{"name":"stdout","output_type":"stream","text":["dict_values(['ram', 'shyam', 'Mohan'])\n","\n"]}],"source":["values_list = d.values()\n","print(values_list)\n","print(type(values_list))"]},{"cell_type":"code","source":["print(d[1])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":176},"id":"Xs4Yo4aTpJXX","executionInfo":{"status":"error","timestamp":1693570087964,"user_tz":-330,"elapsed":422,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"a11b5392-4100-4037-fa5c-55e6bf8fc66b"},"id":"Xs4Yo4aTpJXX","execution_count":12,"outputs":[{"output_type":"error","ename":"NameError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mNameError\u001b[0m: name 'd' is not defined"]}]},{"cell_type":"code","execution_count":null,"id":"f8880432","metadata":{"id":"f8880432","outputId":"b20e52a3-32d1-4310-c11c-065df8379ce2"},"outputs":[{"name":"stdout","output_type":"stream","text":["True\n"]}],"source":["x = 5\n","print(x==5)"]},{"cell_type":"code","execution_count":null,"id":"221a53da","metadata":{"id":"221a53da","outputId":"e1f0896b-389c-4b51-d9b6-a5345bbdf5ac"},"outputs":[{"name":"stdout","output_type":"stream","text":["True\n"]}],"source":["x = None\n","print(x==None)"]},{"cell_type":"markdown","id":"e44d3afd","metadata":{"id":"e44d3afd"},"source":["## Declaring an array with the help of `numpy` module"]},{"cell_type":"code","execution_count":null,"id":"07d9b655","metadata":{"id":"07d9b655"},"outputs":[],"source":["import numpy as np"]},{"cell_type":"code","execution_count":null,"id":"4b5728b4","metadata":{"id":"4b5728b4","outputId":"a6eca41e-d6be-426e-b72b-98954cec77d5"},"outputs":[{"name":"stdout","output_type":"stream","text":["[1 2 3]\n"]}],"source":["a = np.array([1,2,3])\n","print(a)"]},{"cell_type":"code","execution_count":null,"id":"5cab417c","metadata":{"id":"5cab417c","outputId":"abe7215c-97db-41fd-f6f6-5746e593ab08"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[1 2 3]\n"," [4 5 6]\n"," [7 8 9]]\n"]}],"source":["a_2d = np.array([ [1,2,3],\n"," [4,5,6],\n"," [7,8,9]\n"," ])\n","print(a_2d)"]},{"cell_type":"markdown","id":"bef590cb","metadata":{"id":"bef590cb"},"source":["## Assigments:\n","- difference between an array and list"]},{"cell_type":"code","execution_count":null,"id":"9c7c8302","metadata":{"id":"9c7c8302"},"outputs":[],"source":[]}],"metadata":{"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.7.13"},"colab":{"provenance":[]}},"nbformat":4,"nbformat_minor":5} -------------------------------------------------------------------------------- /Module_2_Python_programming_Fundamentals/images/Keywords_list_python.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_2_Python_programming_Fundamentals/images/Keywords_list_python.PNG -------------------------------------------------------------------------------- /Module_2_Python_programming_Fundamentals/images/Keywords_list_python_docs_org.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_2_Python_programming_Fundamentals/images/Keywords_list_python_docs_org.PNG -------------------------------------------------------------------------------- /Module_2_Python_programming_Fundamentals/images/built_in_function.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_2_Python_programming_Fundamentals/images/built_in_function.PNG -------------------------------------------------------------------------------- /Module_2_Python_programming_Fundamentals/lab_M01_001_print_input.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyO1LWeGHz9Tuw0vW9wfoCGY"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["Two basic operations in programming-\n","- Output: displaying something on o/p screen using`print`\n","- Input: `input`"],"metadata":{"id":"oKt4uuu8OavH"}},{"cell_type":"code","source":["print('Hello World!')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"55WuZkL-PWYe","executionInfo":{"status":"ok","timestamp":1692956226455,"user_tz":-330,"elapsed":47,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"af9d49cd-a67a-430a-b75e-72df9350761e"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Hello World!\n"]}]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"2kR1smCVNrWr","executionInfo":{"status":"ok","timestamp":1692956226457,"user_tz":-330,"elapsed":44,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"e83c7991-7749-4aab-ff12-a181fc3eafe3"},"outputs":[{"output_type":"stream","name":"stdout","text":["I am learning python\n"]}],"source":["print('I am learning python')"]},{"cell_type":"markdown","source":["### `syntax using fstring`: - print(f'My name is {NAME}, reg no is {REG NO}')"],"metadata":{"id":"_oOZLc5sdFCq"}},{"cell_type":"code","source":["name = 'XYZ'\n","reg_no = '23BCE2641'"],"metadata":{"id":"aTzFl4e4OZ9u"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["print(f'my names is {name}, reg no is {reg_no}')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"eSg0VxhpQPNX","executionInfo":{"status":"ok","timestamp":1692956226459,"user_tz":-330,"elapsed":36,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8cd805b7-4c70-4f98-ff2b-b915df1c5164"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["my names is XYZ, reg no is 23BCE2641\n"]}]},{"cell_type":"code","source":["print('my names is ' + name + 'reg no is ' + reg_no)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"91zDfio9e3o8","executionInfo":{"status":"ok","timestamp":1692956226460,"user_tz":-330,"elapsed":30,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"a713396d-cccb-4488-ffca-d00cb4753958"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["my names is XYZreg no is 23BCE2641\n"]}]},{"cell_type":"code","source":["'RAM' + 5"],"metadata":{"id":"rVe9rlUKfkkM","colab":{"base_uri":"https://localhost:8080/","height":179},"executionInfo":{"status":"error","timestamp":1692956226461,"user_tz":-330,"elapsed":24,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"172b27f3-c440-4ea2-f6b3-7a50b1570cb7"},"execution_count":null,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34m'RAM'\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str"]}]},{"cell_type":"code","source":["name = 'XYZ'\n","reg_no = 232459 # considering reg_no as integer\n","print(f'my names is {name}, reg ni is {reg_no}')"],"metadata":{"id":"2_7t8ye6TSyQ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["print('my names is {}, reg no is {}'.format(name, reg_no))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"FH2N9it5gEAB","executionInfo":{"status":"ok","timestamp":1692956237337,"user_tz":-330,"elapsed":392,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b26a6f7b-bdb3-43e1-9945-a84760570b23"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["my names is XYZ, reg no is 232459\n"]}]},{"cell_type":"code","source":["print('my names is {1}, reg no is {0}'.format(name, reg_no))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"qo4AEoP2hFh5","executionInfo":{"status":"ok","timestamp":1692956240105,"user_tz":-330,"elapsed":378,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"3253df52-537f-499b-a5d2-c7907908651e"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["my names is 232459, reg no is XYZ\n"]}]},{"cell_type":"code","source":["name = input()\n","reg_no = input() # default type of input function is string\n","print(f'my name is {name}, reg no is {reg_no}')\n","print('type of name varaibles is :', type(name))\n","print('type of reg_no varaibles is :', type(reg_no))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"AI1eTMulkIyh","executionInfo":{"status":"ok","timestamp":1692956252192,"user_tz":-330,"elapsed":9989,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f60bc5de-8b57-470b-d015-dc609a9a661a"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["XYZ\n","23BCE2479\n","my name is XYZ, reg no is 23BCE2479\n","type of name varaibles is : \n","type of reg_no varaibles is : \n"]}]},{"cell_type":"code","source":["name = input()\n","reg_no = int(input()) # converting reg_no fron string to integer (also known as typecasting)\n","print(f'my name is {name}, reg no is {reg_no}')\n","print('type of name varaibles is :', type(name))\n","print('type of reg_no varaibles is :', type(reg_no))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Q3IQCiJElioD","executionInfo":{"status":"ok","timestamp":1692956263511,"user_tz":-330,"elapsed":8908,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"035536c5-6f85-4d61-d44b-4bdee79d1368"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["XYZ\n","234786\n","my name is XYZ, reg no is 234786\n","type of name varaibles is : \n","type of reg_no varaibles is : \n"]}]},{"cell_type":"markdown","source":["## Calculate simple interst, given principal amount (p), rate of interest(r) and time in years respectively. Consider p and t as intergers and r as float"],"metadata":{"id":"9u4kik8lmJcB"}},{"cell_type":"code","source":["p = int(input()) # converting p from string to integer\n","r = float(input()) # converting from string to float\n","t = int(input()) # converting from string to integer\n","si = (p*r*t) /100\n","print(f'simple interest is : {si}')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"JMHVEqsxC7ph","executionInfo":{"status":"ok","timestamp":1692956277249,"user_tz":-330,"elapsed":11805,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"1a8fafd7-a527-4405-fd96-74d59762478d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["68000\n","7.2\n","9\n","simple interest is : 44064.0\n"]}]}]} -------------------------------------------------------------------------------- /Module_2_Python_programming_Fundamentals/lab_M01_003_reserved_keyword_inbuilt_function.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","id":"db40bbfe","metadata":{"id":"db40bbfe"},"source":["# Importing a module and `if` condtional statement\n"," - importing a module\n"," - basic `if` statement"]},{"cell_type":"markdown","id":"d976163d","metadata":{"id":"d976163d"},"source":["## Importing a module"]},{"cell_type":"code","execution_count":1,"id":"e41ed7d4","metadata":{"id":"e41ed7d4","executionInfo":{"status":"ok","timestamp":1692969556946,"user_tz":-330,"elapsed":3,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[],"source":["import numpy"]},{"cell_type":"code","execution_count":2,"id":"5da4f61f","metadata":{"id":"5da4f61f","executionInfo":{"status":"ok","timestamp":1692969557651,"user_tz":-330,"elapsed":2,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[],"source":["import pandas as pd"]},{"cell_type":"code","execution_count":3,"id":"87e331cf","metadata":{"id":"87e331cf","outputId":"561d6bc5-aab9-405e-eef7-d60b15e64d98","colab":{"base_uri":"https://localhost:8080/","height":0},"executionInfo":{"status":"ok","timestamp":1692969558751,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[1 5 7]\n"]}],"source":["import numpy\n","a = numpy.array([1,5, 7])\n","print(a)"]},{"cell_type":"code","source":["import math\n","\n","print(math.sqrt(9))\n","print(math.sqrt(12))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":0},"id":"MJ1BqmGkyyxV","executionInfo":{"status":"ok","timestamp":1692969560752,"user_tz":-330,"elapsed":3,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"77e54fb2-3589-442b-d468-1e0f5a0f3999"},"id":"MJ1BqmGkyyxV","execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["3.0\n","3.4641016151377544\n"]}]},{"cell_type":"code","source":["import sklearn # python machine learning library"],"metadata":{"id":"vWSxODHU9U4G","executionInfo":{"status":"ok","timestamp":1692969563941,"user_tz":-330,"elapsed":2162,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"id":"vWSxODHU9U4G","execution_count":5,"outputs":[]},{"cell_type":"code","execution_count":6,"id":"32b12f03","metadata":{"id":"32b12f03","executionInfo":{"status":"ok","timestamp":1692969570029,"user_tz":-330,"elapsed":6093,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[],"source":["import torch as torch # pytorch - deep learning library by facebook/Meta researc"]},{"cell_type":"code","source":["# refer this to install pytorch library\n","# link: https://saturncloud.io/blog/how-to-install-pytorch-v100-on-google-colab-a-guide-for-data-scientists/\n","\n","!pip3 uninstall --yes torch torchaudio torchvision torchtext torchdata\n","!pip3 install torch torchaudio torchvision torchtext torchdata"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":1610},"id":"MeAVruBOzwVi","executionInfo":{"status":"ok","timestamp":1692969535047,"user_tz":-330,"elapsed":143251,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"6b75bb71-9991-474a-8de2-b1dac5e95b65"},"id":"MeAVruBOzwVi","execution_count":7,"outputs":[{"output_type":"stream","name":"stdout","text":["Found existing installation: torch 2.0.1+cu118\n","Uninstalling torch-2.0.1+cu118:\n"," Successfully uninstalled torch-2.0.1+cu118\n","Found existing installation: torchaudio 2.0.2+cu118\n","Uninstalling torchaudio-2.0.2+cu118:\n"," Successfully uninstalled torchaudio-2.0.2+cu118\n","Found existing installation: torchvision 0.15.2+cu118\n","Uninstalling torchvision-0.15.2+cu118:\n"," Successfully uninstalled torchvision-0.15.2+cu118\n","Found existing installation: torchtext 0.15.2\n","Uninstalling torchtext-0.15.2:\n"," Successfully uninstalled torchtext-0.15.2\n","Found existing installation: torchdata 0.6.1\n","Uninstalling torchdata-0.6.1:\n"," Successfully uninstalled torchdata-0.6.1\n","Collecting torch\n"," Downloading torch-2.0.1-cp310-cp310-manylinux1_x86_64.whl (619.9 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m619.9/619.9 MB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting torchaudio\n"," Downloading torchaudio-2.0.2-cp310-cp310-manylinux1_x86_64.whl (4.4 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.4/4.4 MB\u001b[0m \u001b[31m71.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting torchvision\n"," Downloading torchvision-0.15.2-cp310-cp310-manylinux1_x86_64.whl (6.0 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m6.0/6.0 MB\u001b[0m \u001b[31m69.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting torchtext\n"," Downloading torchtext-0.15.2-cp310-cp310-manylinux1_x86_64.whl (2.0 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m71.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting torchdata\n"," Downloading torchdata-0.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.6/4.6 MB\u001b[0m \u001b[31m65.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch) (3.12.2)\n","Requirement already satisfied: typing-extensions in /usr/local/lib/python3.10/dist-packages (from torch) (4.7.1)\n","Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch) (1.12)\n","Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch) (3.1)\n","Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch) (3.1.2)\n","Collecting nvidia-cuda-nvrtc-cu11==11.7.99 (from torch)\n"," Downloading nvidia_cuda_nvrtc_cu11-11.7.99-2-py3-none-manylinux1_x86_64.whl (21.0 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m21.0/21.0 MB\u001b[0m \u001b[31m60.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cuda-runtime-cu11==11.7.99 (from torch)\n"," Downloading nvidia_cuda_runtime_cu11-11.7.99-py3-none-manylinux1_x86_64.whl (849 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m849.3/849.3 kB\u001b[0m \u001b[31m68.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cuda-cupti-cu11==11.7.101 (from torch)\n"," Downloading nvidia_cuda_cupti_cu11-11.7.101-py3-none-manylinux1_x86_64.whl (11.8 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m11.8/11.8 MB\u001b[0m \u001b[31m101.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cudnn-cu11==8.5.0.96 (from torch)\n"," Downloading nvidia_cudnn_cu11-8.5.0.96-2-py3-none-manylinux1_x86_64.whl (557.1 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m557.1/557.1 MB\u001b[0m \u001b[31m3.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cublas-cu11==11.10.3.66 (from torch)\n"," Downloading nvidia_cublas_cu11-11.10.3.66-py3-none-manylinux1_x86_64.whl (317.1 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m317.1/317.1 MB\u001b[0m \u001b[31m4.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cufft-cu11==10.9.0.58 (from torch)\n"," Downloading nvidia_cufft_cu11-10.9.0.58-py3-none-manylinux1_x86_64.whl (168.4 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m168.4/168.4 MB\u001b[0m \u001b[31m7.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-curand-cu11==10.2.10.91 (from torch)\n"," Downloading nvidia_curand_cu11-10.2.10.91-py3-none-manylinux1_x86_64.whl (54.6 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m54.6/54.6 MB\u001b[0m \u001b[31m15.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cusolver-cu11==11.4.0.1 (from torch)\n"," Downloading nvidia_cusolver_cu11-11.4.0.1-2-py3-none-manylinux1_x86_64.whl (102.6 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m102.6/102.6 MB\u001b[0m \u001b[31m9.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-cusparse-cu11==11.7.4.91 (from torch)\n"," Downloading nvidia_cusparse_cu11-11.7.4.91-py3-none-manylinux1_x86_64.whl (173.2 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m173.2/173.2 MB\u001b[0m \u001b[31m7.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-nccl-cu11==2.14.3 (from torch)\n"," Downloading nvidia_nccl_cu11-2.14.3-py3-none-manylinux1_x86_64.whl (177.1 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m177.1/177.1 MB\u001b[0m \u001b[31m6.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting nvidia-nvtx-cu11==11.7.91 (from torch)\n"," Downloading nvidia_nvtx_cu11-11.7.91-py3-none-manylinux1_x86_64.whl (98 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m98.6/98.6 kB\u001b[0m \u001b[31m12.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hRequirement already satisfied: triton==2.0.0 in /usr/local/lib/python3.10/dist-packages (from torch) (2.0.0)\n","Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from nvidia-cublas-cu11==11.10.3.66->torch) (67.7.2)\n","Requirement already satisfied: wheel in /usr/local/lib/python3.10/dist-packages (from nvidia-cublas-cu11==11.10.3.66->torch) (0.41.1)\n","Requirement already satisfied: cmake in /usr/local/lib/python3.10/dist-packages (from triton==2.0.0->torch) (3.27.2)\n","Requirement already satisfied: lit in /usr/local/lib/python3.10/dist-packages (from triton==2.0.0->torch) (16.0.6)\n","Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from torchvision) (1.23.5)\n","Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from torchvision) (2.31.0)\n","Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.10/dist-packages (from torchvision) (9.4.0)\n","Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from torchtext) (4.66.1)\n","Requirement already satisfied: urllib3>=1.25 in /usr/local/lib/python3.10/dist-packages (from torchdata) (2.0.4)\n","Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch) (2.1.3)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (3.2.0)\n","Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (3.4)\n","Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (2023.7.22)\n","Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch) (1.3.0)\n","Installing collected packages: nvidia-nvtx-cu11, nvidia-nccl-cu11, nvidia-cusparse-cu11, nvidia-curand-cu11, nvidia-cufft-cu11, nvidia-cuda-runtime-cu11, nvidia-cuda-nvrtc-cu11, nvidia-cuda-cupti-cu11, nvidia-cublas-cu11, nvidia-cusolver-cu11, nvidia-cudnn-cu11, torch, torchdata, torchvision, torchtext, torchaudio\n","Successfully installed nvidia-cublas-cu11-11.10.3.66 nvidia-cuda-cupti-cu11-11.7.101 nvidia-cuda-nvrtc-cu11-11.7.99 nvidia-cuda-runtime-cu11-11.7.99 nvidia-cudnn-cu11-8.5.0.96 nvidia-cufft-cu11-10.9.0.58 nvidia-curand-cu11-10.2.10.91 nvidia-cusolver-cu11-11.4.0.1 nvidia-cusparse-cu11-11.7.4.91 nvidia-nccl-cu11-2.14.3 nvidia-nvtx-cu11-11.7.91 torch-2.0.1 torchaudio-2.0.2 torchdata-0.6.1 torchtext-0.15.2 torchvision-0.15.2\n"]},{"output_type":"display_data","data":{"application/vnd.colab-display-data+json":{"pip_warning":{"packages":["nvfuser","torch"]}}},"metadata":{}}]},{"cell_type":"code","source":["import torch\n","print(torch.__version__)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":0},"id":"K-XLlwxBzqPU","executionInfo":{"status":"ok","timestamp":1692969570583,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d3bba101-fcbe-4c81-d5d4-763a9785d079"},"id":"K-XLlwxBzqPU","execution_count":7,"outputs":[{"output_type":"stream","name":"stdout","text":["2.0.1+cu117\n"]}]},{"cell_type":"code","execution_count":8,"id":"93d52497","metadata":{"id":"93d52497","colab":{"base_uri":"https://localhost:8080/","height":0},"executionInfo":{"status":"ok","timestamp":1692969575815,"user_tz":-330,"elapsed":4122,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d3ec3bad-f9b7-4a20-c93e-5cf7b7297ad9"},"outputs":[{"output_type":"stream","name":"stdout","text":["2.12.0\n"]}],"source":["import tensorflow as tf # deep learning library by Google research\n","print(tf.__version__)"]},{"cell_type":"markdown","id":"f6611954","metadata":{"id":"f6611954"},"source":["## Conditional statement -if"]},{"cell_type":"code","execution_count":9,"id":"7916501d","metadata":{"id":"7916501d","outputId":"c7a12a65-9cac-4767-96ed-ab52fde92e19","colab":{"base_uri":"https://localhost:8080/","height":0},"executionInfo":{"status":"ok","timestamp":1692969575816,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["x is greater than 5\n","another line inside if\n","outside if statement\n"]}],"source":["x = 8\n","if x > 5:\n"," print('x is greater than 5')\n"," print('another line inside if')\n","print('outside if statement')"]}],"metadata":{"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.7.13"},"colab":{"provenance":[],"gpuType":"T4"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":5} -------------------------------------------------------------------------------- /Module_3_Control_Structure/lab_06_if_else_for.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","id":"a35b6ac3","metadata":{"id":"a35b6ac3"},"source":["# Condition - If - if-else - if-elif-else multiway if"]},{"cell_type":"markdown","source":["## Lgin to your https://moovit.vit.ac.in/ account"],"metadata":{"id":"dpCLcwxHHN84"},"id":"dpCLcwxHHN84"},{"cell_type":"markdown","source":["## basic if statement"],"metadata":{"id":"ilzp1djHLC6G"},"id":"ilzp1djHLC6G"},{"cell_type":"code","source":["x = 8\n","if x > 5:\n"," print('x is greater than 5')\n"," print('another line inside if')\n","print('outside if statement')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"9G8KajadLG8s","executionInfo":{"status":"ok","timestamp":1693998416777,"user_tz":-330,"elapsed":438,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"da7524b4-ea3f-457c-b970-883b4d5176bb"},"id":"9G8KajadLG8s","execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["x is greater than 5\n","another line inside if\n","outside if statement\n"]}]},{"cell_type":"markdown","id":"2ea68956","metadata":{"id":"2ea68956"},"source":["## to check whether a number is even or odd"]},{"cell_type":"code","execution_count":null,"id":"0e823fd5","metadata":{"id":"0e823fd5","outputId":"b32e2bed-9cdb-4971-f3ce-461592fc5c1c"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter a number :101\n","101 is odd number\n"]}],"source":["num = int(input('Enter a number :'))\n","rem = num %2\n","if rem ==0:\n"," print(' {} is even number'.format(num))\n","else:\n"," print('{} is odd number'.format(num))"]},{"cell_type":"markdown","id":"94c40377","metadata":{"id":"94c40377"},"source":["### Flow chart of above program\n"]},{"cell_type":"markdown","id":"33edc1c5","metadata":{"id":"33edc1c5"},"source":["## To check whether a num is divisible by 2, 3 or 5"]},{"cell_type":"code","execution_count":null,"id":"fd4ea435","metadata":{"id":"fd4ea435","outputId":"3793749f-02b6-4677-aec2-d3cd49f7f90b"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter a num :10\n","Dividble by 2\n","Divisible by 5\n"]}],"source":["num = int(input('Enter a num :'))\n","if num % 2 == 0:\n"," print('Dividble by 2')\n","if num % 3 == 0:\n"," print('Divisible by 3')\n","if num %5 == 0:\n"," print('Divisible by 5')"]},{"cell_type":"markdown","id":"262869d8","metadata":{"id":"262869d8"},"source":["## take a number as input\n","- 1: Sunny\n","- 2 - Cloudy\n","- 3 - Rainy\n","- Other input - invalid input "]},{"cell_type":"code","execution_count":null,"id":"4bb65a01","metadata":{"id":"4bb65a01","outputId":"dc653ebb-ffa9-43db-e264-c77637aaf437"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter a number 1\n","Sunny\n"]}],"source":["num = int(input('Enter a number '))\n","if num ==1:\n"," print('Sunny')\n","elif num ==2: # else if\n"," print('Cloudy')\n","elif num == 3:\n"," print('Rainy')\n","else:\n"," print('Invalid input')"]},{"cell_type":"code","execution_count":null,"id":"52f40691","metadata":{"id":"52f40691","outputId":"15b35456-823d-4268-ef37-d6cb8d7abe24"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter a number 3\n","Rainy\n"]}],"source":["num = int(input('Enter a number '))\n","if num >= 1:\n"," if num ==1:\n"," print('Sunny')\n"," elif num ==2:\n"," print('Cloudy')\n"," elif num == 3:\n"," print('Rainy')\n"," else:\n"," print('Invalid input')\n","else:\n"," print('Invalid input')"]},{"cell_type":"code","execution_count":null,"id":"a5c59f90","metadata":{"id":"a5c59f90","outputId":"ab34d964-9704-490b-8127-734dde264e87"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n","7\n","5\n","9\n"]}],"source":["my_list = [1,7,5, 9]\n","\n","for ii in my_list:\n"," print(ii)"]},{"cell_type":"code","execution_count":null,"id":"969381d3","metadata":{"id":"969381d3","outputId":"3834d46c-81eb-4d3b-d77a-b6a972623897"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n","7\n","5\n","9\n"]}],"source":["for ii in my_list:\n"," print(ii)"]},{"cell_type":"code","execution_count":null,"id":"90aba13e","metadata":{"id":"90aba13e","outputId":"8d675efb-464c-4dd5-ebbc-b75968ee5585"},"outputs":[{"name":"stdout","output_type":"stream","text":["0 : : 1\n","1 : : 7\n","2 : : 5\n","3 : : 9\n"]}],"source":["for i, item in enumerate(my_list):\n"," print(i, ': :', item)"]},{"cell_type":"code","execution_count":null,"id":"6389e2c3","metadata":{"id":"6389e2c3","outputId":"5fae26a4-72c9-47cd-d174-693159070a74"},"outputs":[{"name":"stdout","output_type":"stream","text":[": : (0, 1)\n",": : (1, 7)\n",": : (2, 5)\n",": : (3, 9)\n"]}],"source":["for item in enumerate(my_list):\n"," print(': :', item)"]},{"cell_type":"code","execution_count":null,"id":"e18ca66d","metadata":{"id":"e18ca66d","outputId":"37d0e5b4-eb47-4789-9f99-7da3203deec7"},"outputs":[{"name":"stdout","output_type":"stream","text":["Help on class range in module builtins:\n","\n","class range(object)\n"," | range(stop) -> range object\n"," | range(start, stop[, step]) -> range object\n"," | \n"," | Return an object that produces a sequence of integers from start (inclusive)\n"," | to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\n"," | start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\n"," | These are exactly the valid indices for a list of 4 elements.\n"," | When step is given, it specifies the increment (or decrement).\n"," | \n"," | Methods defined here:\n"," | \n"," | __bool__(self, /)\n"," | self != 0\n"," | \n"," | __contains__(self, key, /)\n"," | Return key in self.\n"," | \n"," | __eq__(self, value, /)\n"," | Return self==value.\n"," | \n"," | __ge__(self, value, /)\n"," | Return self>=value.\n"," | \n"," | __getattribute__(self, name, /)\n"," | Return getattr(self, name).\n"," | \n"," | __getitem__(self, key, /)\n"," | Return self[key].\n"," | \n"," | __gt__(self, value, /)\n"," | Return self>value.\n"," | \n"," | __hash__(self, /)\n"," | Return hash(self).\n"," | \n"," | __iter__(self, /)\n"," | Implement iter(self).\n"," | \n"," | __le__(self, value, /)\n"," | Return self<=value.\n"," | \n"," | __len__(self, /)\n"," | Return len(self).\n"," | \n"," | __lt__(self, value, /)\n"," | Return self integer -- return number of occurrences of value\n"," | \n"," | index(...)\n"," | rangeobject.index(value) -> integer -- return index of value.\n"," | Raise ValueError if the value is not present.\n"," | \n"," | ----------------------------------------------------------------------\n"," | Static methods defined here:\n"," | \n"," | __new__(*args, **kwargs) from builtins.type\n"," | Create and return a new object. See help(type) for accurate signature.\n"," | \n"," | ----------------------------------------------------------------------\n"," | Data descriptors defined here:\n"," | \n"," | start\n"," | \n"," | step\n"," | \n"," | stop\n","\n"]}],"source":["help(range)"]},{"cell_type":"code","execution_count":null,"id":"604706a5","metadata":{"id":"604706a5","outputId":"b663398b-b495-4fff-ee3c-fbdfa9444ac3"},"outputs":[{"name":"stdout","output_type":"stream","text":["0\n","1\n","2\n","3\n","4\n","5\n","6\n"]}],"source":["for num in range(7):\n"," print(num)"]},{"cell_type":"code","execution_count":null,"id":"588edfbd","metadata":{"id":"588edfbd","outputId":"6145e4de-7ff6-41af-9f4d-b58dfda18daf"},"outputs":[{"name":"stdout","output_type":"stream","text":["7\n","5\n","3\n","1\n"]}],"source":["for num in range(7, 0, -2):\n"," print(num)"]},{"cell_type":"code","execution_count":null,"id":"833985b8","metadata":{"id":"833985b8","outputId":"0d5dae13-ddae-43c3-b54c-4abc502a36d2"},"outputs":[{"name":"stdout","output_type":"stream","text":["2 is even\n","4 is even\n","10 is even\n","12 is even\n"]}],"source":["# 1\n","l = [2,4,7,13,10, 12]\n","for item in l:\n"," if item %2 ==0:\n"," print(\"{} is even\".format(item))"]},{"cell_type":"code","execution_count":null,"id":"0668a8af","metadata":{"id":"0668a8af","outputId":"7809d18f-2346-4884-b625-5bf663b811f1"},"outputs":[{"name":"stdout","output_type":"stream","text":["48\n"]}],"source":["list_sum = 0\n","for item in l:\n"," list_sum = list_sum + item\n","print(list_sum)"]},{"cell_type":"markdown","id":"d22f2922","metadata":{"id":"d22f2922"},"source":["#### Given a list of integers, and a number n.\n","- Find whether number n is present is list.\n","- Also find the index on n in the list\n"]},{"cell_type":"code","execution_count":null,"id":"5f75f235","metadata":{"id":"5f75f235"},"outputs":[],"source":["l = [2,4,7,13,10,12]\n","n = int(input())\n","found = False\n","for i, item in enumerate(l):\n"," if n == item:\n"," found = True\n"," break\n","if found:\n"," print(' Num found at index {}'.format(i))\n","else:\n"," print('Num not found')"]}],"metadata":{"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.7.13"},"colab":{"provenance":[]}},"nbformat":4,"nbformat_minor":5} -------------------------------------------------------------------------------- /Module_3_Control_Structure/lab_07_while_loop_break_continue_pass.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","id":"510fed9d","metadata":{"id":"510fed9d"},"source":["# While loop\n","- while loop\n","- keywords `break`, `continue`, and `pass` inside loop\n","- flags inside loop"]},{"cell_type":"markdown","id":"b4c11adf","metadata":{"id":"b4c11adf"},"source":["## while loop"]},{"cell_type":"code","execution_count":null,"id":"b119f60f","metadata":{"id":"b119f60f","outputId":"3110ff80-cf1b-4416-fd36-31eb457bd1e8"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n","2\n","3\n","4\n","5\n"]}],"source":["#counting number\n","current_number = 1\n","while current_number <= 5:\n"," print(current_number)\n"," current_number += 1"]},{"cell_type":"code","execution_count":null,"id":"58c25453","metadata":{"id":"58c25453"},"outputs":[],"source":["#counting number\n","current_number = 1\n","while current_number <= 5:\n"," print(current_number)\n"," current_number += 1\n","print('Outside while loop')"]},{"cell_type":"code","source":["#counting number\n","current_number = 1\n","while current_number <= 5:\n"," print(current_number)\n"," current_number += 1\n"," if current_number ==4:\n"," break\n","else:\n"," print('\\t Executed else of while')\n","print('Outside while loop')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"oAVALtSHTHeG","executionInfo":{"status":"ok","timestamp":1695208830136,"user_tz":-330,"elapsed":598,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"6593153d-3da9-4b47-8699-717f32d8757b"},"id":"oAVALtSHTHeG","execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["1\n","2\n","3\n","Outside while loop\n"]}]},{"cell_type":"code","execution_count":null,"id":"b88393d0","metadata":{"id":"b88393d0","outputId":"65dbb795-96c0-48ee-acaa-ddb8b76c3b68"},"outputs":[{"name":"stdout","output_type":"stream","text":["Alexa here! your message or quit to close:: play a dance song\n","Your message is : play a dance song \n","\n","Alexa here! your message or quit to close:: over the sky\n","Your message is : over the sky \n","\n","Alexa here! your message or quit to close:: in the ight\n","Your message is : in the ight \n","\n","Alexa here! your message or quit to close:: over the cloud\n","Your message is : over the cloud \n","\n","Alexa here! your message or quit to close:: in the meta-verse\n","Your message is : in the meta-verse \n","\n","Alexa here! your message or quit to close:: quit\n","Your message is : quit \n","\n","\n"," Quitting Alexa\n"]}],"source":["# Alexa chatting\n","message = ''\n","prompt = 'Alexa here! your message or quit to close:: '\n","while message != 'quit':\n"," message = input(prompt)\n"," print(f'Your message is : {message} \\n')\n","print(f'\\n Quitting Alexa')"]},{"cell_type":"code","execution_count":null,"id":"dc608ff7","metadata":{"id":"dc608ff7","outputId":"81e4f93b-3c0d-4d8f-b959-2c96ddde970c"},"outputs":[{"name":"stdout","output_type":"stream","text":["Alexa here! please enter your message or quit to closesing me a dance song\n","Your message is : sing me a dance song \n","\n","Alexa here! please enter your message or quit to closeover the sky\n","Your message is : over the sky \n","\n","Alexa here! please enter your message or quit to closein the night\n","Your message is : in the night \n","\n","Alexa here! please enter your message or quit to closeover the monn\n","Your message is : over the monn \n","\n","Alexa here! please enter your message or quit to closeon the cloud\n","Your message is : on the cloud \n","\n","Alexa here! please enter your message or quit to closein the meta-verse\n","Your message is : in the meta-verse \n","\n","Alexa here! please enter your message or quit to closequit\n","Your message is : quit \n","\n"]}],"source":["# Alexa chatting\n","message = ''\n","prompt = 'Alexa here! your message or quit to close:: '\n","while message != 'quit':\n"," message = input(prompt)\n"," print(f'Your message is : {message} \\n')\n","print(f'\\n Quitting Alexa')"]},{"cell_type":"code","execution_count":null,"id":"f21a638d","metadata":{"id":"f21a638d","outputId":"5d0dbe99-01d7-468a-89ca-a6978a432b9e"},"outputs":[{"name":"stdout","output_type":"stream","text":["Alexa here! please enter your message or quit to closesing me a song\n","Your message is : sing me a song\n","Alexa here! please enter your message or quit to closequit\n","Alexa signing out! Have a good day!\n"]}],"source":["# Alexa chatting with signout message\n","prompt = 'Alexa here! please enter your message or quit to close:: '\n","message= ''\n","while message != 'quit':\n"," message = input(prompt)\n"," if message == 'quit':\n"," print('Alexa signing out! Have a good day!')\n"," else:\n"," print(f'Your message is : {message}')\n"]},{"cell_type":"markdown","id":"43756ae0","metadata":{"id":"43756ae0"},"source":["### **Assignment** how to quit above program for quit, Quit, QUIT ?"]},{"cell_type":"code","execution_count":null,"id":"67aaa53c","metadata":{"id":"67aaa53c","outputId":"b60c7926-cdde-44e6-f133-9632bbd4def1"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter the target: 19\n","step = 1, num = 2, target=19\n","step = 2, num = 4, target=19\n","step = 3, num = 8, target=19\n","step = 4, num = 16, target=19\n","step = 5, num = 32, target=19\n"]}],"source":["## Using a flag - to reach the power of two (2^(num) just greatee\n","## than equal to target\n","num = 1\n","step = 0\n","target = int(input('Enter the target: '))\n","while num <= target:\n"," num = num *2\n"," step +=1\n"," print(f'step = {step}, num = {num}, target={target}')"]},{"cell_type":"code","execution_count":null,"id":"bb90f06f","metadata":{"id":"bb90f06f","outputId":"6eefd0f3-1d62-4822-c64d-7bdd372ab258"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter the target: 8\n","step = 1, num = 2, target=8\n","step = 2, num = 4, target=8\n","step = 3, num = 8, target=8\n","step = 4, num = 16, target=8\n","step = 5, num = 32, target=8\n","\n"," 2^5 >= 8\n"]}],"source":["## Using a flag - to reach the power of two just less than equal to 2^n\n","num = 1\n","step = 0\n","target = int(input('Enter the target: '))\n","reached = False\n","while not reached:\n"," if num >= target:\n"," reached= True\n"," num = num *2\n"," step +=1\n"," print(f'step = {step}, num = {num}, target={target}')\n","\n","if reached:\n"," print(f'\\n 2^{step} >= {target}')\n"]},{"cell_type":"markdown","id":"dc4bf8a1","metadata":{"id":"dc4bf8a1"},"source":["### How to crrect above program ?"]},{"cell_type":"code","execution_count":null,"id":"49a8deb7","metadata":{"id":"49a8deb7","outputId":"5ad490d9-fa21-497c-a1e1-ba708c37f25c"},"outputs":[{"name":"stdout","output_type":"stream","text":["Enter the target: 16\n","step = 1, num = 2, target=16\n","step = 2, num = 4, target=16\n","step = 3, num = 8, target=16\n","step = 4, num = 16, target=16\n","\n"," 2^4 >= 16\n"]}],"source":["## Using a flag - to reach the power of two just less than equal to 2^n\n","num = 1\n","step = 0\n","target = int(input('Enter the target: '))\n","reached = False\n","while not reached:\n"," if num >= target:\n"," reached= True\n"," else:\n"," num = num *2\n"," step +=1\n"," print(f'step = {step}, num = {num}, target={target}')\n","\n","if reached:\n"," print(f'\\n 2^{step} >= {target}')"]},{"cell_type":"markdown","id":"b8baff07","metadata":{"id":"b8baff07"},"source":["## `break` vs `continue` with `for` loop\n","**Link**: https://pythonclass.in/difference-between-break-and-continue.php"]},{"cell_type":"code","execution_count":null,"id":"04c1e11c","metadata":{"id":"04c1e11c","outputId":"318f01b0-6b2a-4182-adaf-75316d63d0c7"},"outputs":[{"name":"stdout","output_type":"stream","text":["i = 2, count_of_students=10\n"]}],"source":["# to count number of student in the right side of the class\n","student_list = [ 5, 5, 4, 5, 5, 5, 3] # no of students in each row\n","count_of_students = 0\n","for i, item in enumerate(student_list):\n"," if i ==2:\n"," break\n"," count_of_students += item\n","\n","print(f'i = {i}, count_of_students={count_of_students}')\n"]},{"cell_type":"code","execution_count":null,"id":"8d98224e","metadata":{"id":"8d98224e","outputId":"e653be39-74dc-4d74-f64d-66024242e223"},"outputs":[{"name":"stdout","output_type":"stream","text":["i = 6, count_of_students=28\n"]}],"source":["# to count number of student in the right side of the class\n","student_list = [ 5, 5, 4, 5, 5, 5, 3] # no of students in each row\n","count_of_students = 0\n","for i, item in enumerate(student_list):\n"," if i ==2:\n"," continue\n"," count_of_students += item\n","\n","print(f'i = {i}, count_of_students={count_of_students}')"]},{"cell_type":"code","execution_count":null,"id":"1d632df6","metadata":{"id":"1d632df6","outputId":"f7bf682a-7875-4498-9768-f03713683232"},"outputs":[{"name":"stdout","output_type":"stream","text":["[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"]}],"source":["my_list = list(range(1,11))\n","print(my_list)"]},{"cell_type":"code","execution_count":null,"id":"eb7f98d0","metadata":{"id":"eb7f98d0"},"outputs":[],"source":[]},{"cell_type":"code","execution_count":null,"id":"30de9d73","metadata":{"id":"30de9d73","outputId":"6956f53c-ef67-47ed-8f3f-844227ef27b9"},"outputs":[{"name":"stdout","output_type":"stream","text":["num =1, num^2 = 1, num^3=1\n","num =2, num^2 = 4, num^3=8\n","num =3, num^2 = 9, num^3=27\n","num =4, num^2 = 16, num^3=64\n","num =5, num^2 = 25, num^3=125\n","num =6, num^2 = 36, num^3=216\n","num =7, num^2 = 49, num^3=343\n","num =8, num^2 = 64, num^3=512\n","num =9, num^2 = 81, num^3=729\n","num =10, num^2 = 100, num^3=1000\n"]}],"source":["for num in my_list:\n"," print(f'num ={num}, num^2 = {num**2}, num^3={num**3}')"]},{"cell_type":"markdown","id":"51945d4c","metadata":{"id":"51945d4c"},"source":["#### `break` and `continue` if num==5 `for` loop"]},{"cell_type":"code","execution_count":null,"id":"c8d32788","metadata":{"id":"c8d32788","outputId":"a822cb9d-e20b-4b5b-fc7b-a2c450f97c0f"},"outputs":[{"name":"stdout","output_type":"stream","text":["num =1, num^2 = 1, num^3=1\n","num =2, num^2 = 4, num^3=8\n","num =3, num^2 = 9, num^3=27\n","num =4, num^2 = 16, num^3=64\n","num =6, num^2 = 36, num^3=216\n","num =7, num^2 = 49, num^3=343\n","num =8, num^2 = 64, num^3=512\n","num =9, num^2 = 81, num^3=729\n","num =10, num^2 = 100, num^3=1000\n"]}],"source":["# skip the processing for num=5\n","for num in my_list:\n"," if num == 5:\n"," continue\n"," print(f'num ={num}, num^2 = {num**2}, num^3={num**3}')"]},{"cell_type":"code","execution_count":null,"id":"7ca06347","metadata":{"id":"7ca06347","outputId":"43055062-b52f-40d6-9c7a-d965ad722662"},"outputs":[{"name":"stdout","output_type":"stream","text":["num =1, num^2 = 1, num^3=1\n","num =2, num^2 = 4, num^3=8\n","num =3, num^2 = 9, num^3=27\n","num =4, num^2 = 16, num^3=64\n"]}],"source":["# break the processing of loop if your get num ==5\n","for num in my_list:\n"," if num == 5:\n"," break\n"," print(f'num ={num}, num^2 = {num**2}, num^3={num**3}')"]},{"cell_type":"markdown","id":"2b0bde76","metadata":{"id":"2b0bde76"},"source":["#### `break` and `continue` for even number inside `for` loop"]},{"cell_type":"code","execution_count":null,"id":"c43c31ae","metadata":{"id":"c43c31ae","outputId":"51d57696-5410-4d42-f74a-9d52e69799be"},"outputs":[{"name":"stdout","output_type":"stream","text":["num =1, num^2 = 1, num^3=1\n","num =3, num^2 = 9, num^3=27\n","num =5, num^2 = 25, num^3=125\n","num =7, num^2 = 49, num^3=343\n","num =9, num^2 = 81, num^3=729\n"]}],"source":["# skip the processing for even numbers\n","for num in my_list:\n"," if num %2==0:\n"," continue\n"," print(f'num ={num}, num^2 = {num**2}, num^3={num**3}')"]},{"cell_type":"code","execution_count":null,"id":"c0e3bc22","metadata":{"id":"c0e3bc22","outputId":"d9f94f27-2052-43aa-b693-774a7c2f99b3"},"outputs":[{"name":"stdout","output_type":"stream","text":["num =1, num^2 = 1, num^3=1\n"]}],"source":["# break the processing if you encountered an even number\n","for num in my_list:\n"," if num %2==0:\n"," break\n"," print(f'num ={num}, num^2 = {num**2}, num^3={num**3}')"]},{"cell_type":"markdown","id":"b64133db","metadata":{"id":"b64133db"},"source":["### infinite loop"]},{"cell_type":"code","execution_count":null,"id":"b5f6c512","metadata":{"id":"b5f6c512","outputId":"ce92744e-8eb4-4ef7-fe2a-234ed2f2f405"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n","2\n","3\n","4\n","5\n"]}],"source":["x = 1\n","while x <= 5:\n"," print(x)\n"," x += 1"]},{"cell_type":"code","execution_count":null,"id":"2eae0c62","metadata":{"id":"2eae0c62","outputId":"1af8553a-afe9-4ebe-fb0e-57b66580e979"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n","2\n","3\n","4\n","5\n"]}],"source":["# Infinite loop\n","x = 1\n","while x <= 5:\n"," print(x)\n"," # x +=1"]},{"cell_type":"markdown","id":"7b79cba1","metadata":{"id":"7b79cba1"},"source":["### Alexa chatting with signout message using `break`"]},{"cell_type":"code","execution_count":null,"id":"ddcc4702","metadata":{"id":"ddcc4702","outputId":"afb54c61-eef9-4cbf-cdad-a12ace420404"},"outputs":[{"name":"stdout","output_type":"stream","text":["Alexa here! please enter your message or quit to closehi Elexa\n","\n","Your message is : hi Elexa\n","Alexa here! please enter your message or quit to closeRead a book for me\n","\n","Your message is : Read a book for me\n","Alexa here! please enter your message or quit to closeIncrease the volume\n","\n","Your message is : Increase the volume\n","Alexa here! please enter your message or quit to closequit\n","\n","Alexa signing out! Have a good day!\n"]}],"source":["### # Alexa chatting with signout message\n","prompt = 'Alexa here! please enter your message or quit to close'\n","message= ''\n","while True:\n"," message = input(prompt)\n"," if message == 'quit':\n"," print('\\nAlexa signing out! Have a good day!')\n"," break\n"," else:\n"," print(f'\\nYour message is : {message}')"]}],"metadata":{"kernelspec":{"display_name":"Python [conda env:miniconda3-BCSE101E] *","language":"python","name":"conda-env-miniconda3-BCSE101E-py"},"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.7.13"},"colab":{"provenance":[]}},"nbformat":4,"nbformat_minor":5} -------------------------------------------------------------------------------- /Module_3_Control_Structure/lab_08_for_loop.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyPmgNqtlj1Ylc1CiluXgy7g"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# For loop\n","- looping over a `sequence` or `iterable` or `collections`\n"," - string: a sequnce of character\n"," - ordered collection: list, tuple, numpy array, dictionary after python 3.6 and 3.7\n"," - unorderd collection: set\n","\n","- For loop syntax\n","\n","- For loop with else statement\n","\n","- Nested for loop\n"," - dependent nested for loop\n"," - independent nested for loop\n","\n","- break, continue, pass\n","\n","- Examples\n"," - to find the sum of numbers in a list\n"," - to check whether a number is prime or not\n"," - to find the factorial of a number"],"metadata":{"id":"uiscHPawXAal"}},{"cell_type":"markdown","source":[],"metadata":{"id":"HcIcDuhXgcYg"}},{"cell_type":"markdown","source":["for loop syntax over sequqnce/iterable/collections"],"metadata":{"id":"naJV6re-ZpK6"}},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"U_VUyPhEPdOz","executionInfo":{"status":"ok","timestamp":1695279444792,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"593dac51-e766-4063-ff25-5ebb4393b543"},"outputs":[{"output_type":"stream","name":"stdout","text":["Python\n","C\n","C++\n","Java\n"," Maths\n"]}],"source":["lang_list = ['Python', 'C', 'C++', 'Java', ' Maths']\n","for item in lang_list:\n"," print(item)\n"]},{"cell_type":"code","source":["name = \"Durgesh Kumar\"\n","word_list = name.split(' ')\n","print(word_list)\n","print(len(word_list))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"z1A99GoBYt0u","executionInfo":{"status":"ok","timestamp":1695210238700,"user_tz":-330,"elapsed":426,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"90c7804c-0b04-491a-d5a3-5eae4e603b13"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["['Durgesh', 'Kumar']\n","2\n"]}]},{"cell_type":"code","source":["name = \"Durgesh Kumar\"\n","space_count =0\n","for ch in name:\n"," if ch == ' ':\n"," space_count += 1\n","print(f'space_count={space_count}')\n","print(f'word_count={space_count+1}')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Avn6ecGCa0Xc","executionInfo":{"status":"ok","timestamp":1695210685120,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b48f6fcc-4a2d-41bf-a6a5-2d1d18f5e444"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["space_count=1\n","word_count=2\n"]}]},{"cell_type":"code","source":["grade= { }\n","grade['23BCE046'] = 'A'\n","grade['23BCE048'] = 'S'\n","grade['23BCE050'] = 'B'"],"metadata":{"id":"7aWb6-wQZz9y"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["for roll in grade:\n"," print(roll, grade[roll])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"pB_1vMZVaHID","executionInfo":{"status":"ok","timestamp":1695279330926,"user_tz":-330,"elapsed":1143,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"6aebf7d5-d323-4719-bd0e-a952580e0d0d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["23BCE046 A\n","23BCE048 S\n","23BCE050 B\n"]}]},{"cell_type":"markdown","source":["### `for` with `range`"],"metadata":{"id":"ntIa0FQ4ZimK"}},{"cell_type":"markdown","source":[],"metadata":{"id":"_V4LB6CxgdX-"}},{"cell_type":"code","source":["for i in range(6):\n"," print(i)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"WL4hrCsLYuBs","executionInfo":{"status":"ok","timestamp":1695211320915,"user_tz":-330,"elapsed":9,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f678e908-e510-4ba6-da33-4a5ad84178df"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["0\n","1\n","2\n","3\n","4\n","5\n"]}]},{"cell_type":"markdown","source":["### `for` with item and index using `enumerate`"],"metadata":{"id":"k8DEyh2RaNpp"}},{"cell_type":"code","source":["lang_list = ['Python', 'C', 'C++', 'Java', ' Maths']\n","for index, item in enumerate(lang_list):\n"," print(index, item)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Pz4dwSk0aUq6","executionInfo":{"status":"ok","timestamp":1695279611596,"user_tz":-330,"elapsed":415,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8794b3de-bb3e-4a9f-ab24-1637273d6b6c"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["0 Python\n","1 C\n","2 C++\n","3 Java\n","4 Maths\n"]}]},{"cell_type":"code","source":["lang_list = ['Python', 'C', 'C++', 'Java', ' Maths']\n","for index, item in enumerate(lang_list, 1):\n"," print(index, item)\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"INIyu00figOv","executionInfo":{"status":"ok","timestamp":1695279625378,"user_tz":-330,"elapsed":427,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"59e663f2-db3d-40ef-a27d-9a4892f25fab"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["1 Python\n","2 C\n","3 C++\n","4 Java\n","5 Maths\n"]}]},{"cell_type":"code","source":["lang_list = ['Python', 'C', 'C++', 'Java', ' Maths']\n","for index, item in enumerate(lang_list[2:], 1):\n"," print(index, item)\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"jND4RLp0iw4_","executionInfo":{"status":"ok","timestamp":1695279761122,"user_tz":-330,"elapsed":429,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"55868bd6-9d77-4315-8101-3213b3ee7912"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["1 C++\n","2 Java\n","3 Maths\n"]}]},{"cell_type":"markdown","source":["## prime number"],"metadata":{"id":"y47YDVJhjuGw"}},{"cell_type":"code","source":["num = int(input())\n","for num == int():\n"," if num%1==0 and num%num ==0:\n"," print('IS PRIME')\n"," else:\n"," print('NOT PRIME')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":143},"id":"BsMnb0IbjwB-","executionInfo":{"status":"error","timestamp":1695280386889,"user_tz":-330,"elapsed":448,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"a8e82b73-7b3e-4c66-8b28-3d0b542113b1"},"execution_count":null,"outputs":[{"output_type":"error","ename":"SyntaxError","evalue":"ignored","traceback":["\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m for num == int():\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"]}]},{"cell_type":"code","source":["num = int(input()) #1\n","if num >1:\n"," for i in range(2, int(num/2) +1 ):\n"," if num % i ==0: # num%1 ==0\n"," print('IS PRIME')\n"," else:\n"," print('NOT PRIME')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"jSJQiIi9lGfu","executionInfo":{"status":"ok","timestamp":1695281136684,"user_tz":-330,"elapsed":5148,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"1a22ef0d-2a26-4389-9c7c-adff7f2f75a8"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["9\n","NOT PRIME\n","IS PRIME\n","NOT PRIME\n"]}]},{"cell_type":"code","source":["num = int(input()) #1\n","if num >1:\n"," for i in range(2, int(num/2) +1 ):\n"," if num % i ==0: # num%1 ==0\n"," print('NOT PRIME')\n"," break\n"," else:\n"," print('IS PRIME')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"62jk6wtpoTOR","executionInfo":{"status":"ok","timestamp":1695281258435,"user_tz":-330,"elapsed":2227,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"00f0cd3e-a312-4598-9c0b-a178a036138f"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["9\n","NOT PRIME\n"]}]},{"cell_type":"code","source":["num = int(input())\n","is_prime = True\n","for i in range(2, num):\n"," if num %i ==0:\n"," is_prime = False\n"," break\n","\n","if is_prime:\n"," print(f'{num} is prime')\n","else:\n"," print(f'{num} is NOT prime')\n"],"metadata":{"id":"BKoOY6v2pJ6Q"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["## Nested for loop\n","- independent loop\n","- dependent loop"],"metadata":{"id":"73dudI_MO_Sa"}},{"cell_type":"code","source":["# independent loop\n","list1 = ['I am ', 'You are ']\n","list2 = ['healthy', 'fine', 'geek']\n","for item1 in list1:\n"," for item2 in list2:\n"," print(item1, item2)\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"GjKG3AYDPTKD","executionInfo":{"status":"ok","timestamp":1695811522858,"user_tz":-330,"elapsed":18,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"4048b9a1-abb8-4bdc-f2de-18f07ebbe187"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["I am healthy\n","I am fine\n","I am geek\n","You are healthy\n","You are fine\n","You are geek\n"]}]},{"cell_type":"code","source":["# independent loop\n","for i in range(4):\n"," for j in range(100, 102):\n"," print(i, j)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"pCNKLT5EPix8","executionInfo":{"status":"ok","timestamp":1695811578467,"user_tz":-330,"elapsed":13,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b06535cc-d3b3-42cd-cc55-7f4f1f71431d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["0 100\n","0 101\n","1 100\n","1 101\n","2 100\n","2 101\n","3 100\n","3 101\n"]}]},{"cell_type":"markdown","source":["### pattern printing\n","![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIwAAACVCAYAAACKGRJtAAAFV0lEQVR4Xu2dsWsUQRTG37VXB8EmxtIUopViGjsVe4tEBJFoEYJYWCUgQlJZSJAUIiEgJoW9on+AqcUiVsHLNWIIpAikTNxzQw6TQPbN7M3M2/lZv8n75vt+zu3CPLZ1fezmgfAPByo60AKYik5R9s8BgAEElQMAo7KLYoCBAZUDAKOyi2KAgQGVAwCjsotigIEBlQMAo7KLYoCBAZUDAKOyi2KAgQGVAwCjsotigIEBlQMAo7KLYoCBAZUDtQAzMbcko+uPZGZV1Ztigw54AHNP5t9fkvUHL+XXszdy98+0zGw+lXfjIstTC7Jm0Awkn+2ABzAiNwpQpq6KdLrbRachGRluS+cLJ83Zttut8AKm3PY1eb74WK7sfJWJ2Y92nUB5JQe8gClPmLbs7XZla4cTppLjxos8gOEZxnj2TvI9gOn34y3JyXuTi2oBxuTOEe3kAMA42ZbvIoDJN3unnQOMk235LgKYfLN32jnAONmW7yKAyTd7p50DjJNt+S4CmHyzd9o5wDjZlu8igMk3e6edA4yTbfkuAph8s3faOcA42ZbvIoDJN3unnQOMk235LgKYfLN32nktwNRy4278hayM/uQiuVOM4RZ5AFPPnd4j2HozTXd+y+TsZjGFcF9kdVpefQtnBJ2qOeABTE1zSWMFKE8ui3SLyYNC87nhYWl3GVmpFl/4Ki9gSrn1zCWVIyvb8rmYpFwJ7wMdKzrgBUwtc0mHJ0x7d086O9ucMBWDi1XmAQzPMLFCi9nXA5i+bN6SYkYYtnctwISVTLeYDgBMTPcN9gYYg6HFlAwwMd032BtgDIYWUzLAxHTfYG+AMRhaTMkAE9N9g70BxmBoMSUDTEz3DfYGGIOhxZQMMDHdN9gbYAyGFlMywMR032BvgDEYWkzJABPTfYO9awEmmQtUjKoMHEEPYNK5osmoysA5OWrgAUxCYyaMqgQjxguYUmU6YyaMqgyeGy9gkhkzYVRl8KQcdvAAhmeYYCkl1MgDmP4ueEtKKNEBS6kFmAFr5M8n5ADAJBSGBSkAYyGlhDQCTEJhWJACMBZSSkgjwCQUhgUpAGMhpYQ0AkxCYViQAjAWUkpII8AkFIYFKQBjIaWENAJMQmFYkAIwFlJKSCPAJBSGBSkAYyGlhDQCTEJhWJACMBZSSkhjLcA06sZd737wuMjy1IKsJRRUKlI8gGnWnd7ehfaH8kEmX1+Q+cXz8qkA5uLckoyuP5KZ1VTiiq/DA5imzSX1/gPckpHiMzydXi7FZ3hGdn/IIifNf5R6AVP+pYbNJfXGbW8Pyfe3fODrtPPMC5hmzSUdnjDFZ3j2is/wbHHCnPr75wEMzzDxnyjCK/AApi+Wt6TwwcXqWAswscTTN7wDABPec9MdAcZ0fOHFA0x4z013BBjT8YUXDzDhPTfdEWBMxxdePMCE99x0R4AxHV948QAT3nPTHQHGdHzhxQNMeM9NdwQY0/GFFw8w4T033RFgTMcXXjzAhPfcdMdagOEC1TEGGjyq4gEMVzSPHxU5jKp4AMOYycnfluaPqngBUxrGmMkJcBo8quIFDGMmx1Fp/qiKBzA8w/AM4/jCx1sSb0mO6LCs6Q54/CQ13Rr2d5oDAAMXKgcARmUXxQADAyoHAEZlF8UAAwMqBwBGZRfFAAMDKgcARmUXxQADAyoHAEZlF8UAAwMqBwBGZRfFAAMDKgcARmUXxQADAyoHAEZlF8UAAwMqBwBGZRfFAAMDKgcARmUXxQADAyoHAEZlF8UAAwMqBwBGZRfFAAMDKgdaGxsbB6oVFGftQGt/fx9gskZAt3mA0fmVfTXAZI+AzoC/RCs8JWkNmE8AAAAASUVORK5CYII=)"],"metadata":{"id":"aeFxIi_sRElE"}},{"cell_type":"code","source":["\n"],"metadata":{"id":"z4STju4zPzyy"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["- 1\n","-2 2\n","-3 3 3\n","-4 4 4 4"],"metadata":{"id":"zZHBeOXtRxX0"}},{"cell_type":"code","source":["\n","n = int(input())\n","for i in range(n+1):\n"," for j in range(i):\n"," print(i, end=\"\")\n"," print()"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"augYkrA5fz8l","executionInfo":{"status":"ok","timestamp":1695815947541,"user_tz":-330,"elapsed":3009,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"646bc272-fce6-4e26-d6a3-a30200a512b0"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["5\n","\n","1\n","22\n","333\n","4444\n","55555\n"]}]},{"cell_type":"code","source":["for i in range(n+1):\n"," print(str(i) * i)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"JYIuaDXIgeze","executionInfo":{"status":"ok","timestamp":1695815982837,"user_tz":-330,"elapsed":8,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"67285809-8448-4f5d-a29b-5ae68d2a281c"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","1\n","22\n","333\n","4444\n","55555\n"]}]},{"cell_type":"code","source":["n = int(input())\n","for i in range(1,n):\n"," n *= i\n","print(n)\n"],"metadata":{"id":"4iq8FhzcRCqb"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["8*7*6*5*4*3*2"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"qXg52qBcZglM","executionInfo":{"status":"ok","timestamp":1695814138452,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"aed02a79-120f-4930-e6fd-60a68f6d8bcb"},"execution_count":null,"outputs":[{"output_type":"execute_result","data":{"text/plain":["40320"]},"metadata":{},"execution_count":7}]}]} -------------------------------------------------------------------------------- /Module_4_Collections/lab_09_dictionary.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Dictionary\n","- a key-value pair.\n","- used to store data values like a map (hashing). \n","\n","**Dictionary in Python** is a collection of keys values, used to store data values like a map, which, \n","unlike other data types which hold only a single value as an element."],"metadata":{"id":"ZA97lVYYWFie"}},{"cell_type":"markdown","source":["### Properties of Keys and Values of dictionary\n","**Keys**:\n","- keys in a dictionary can not be repeated.\n","- keys must be immutable. \n","\n","**Values**\n","- Values in a dictionary can be of any data type.\n","- Values can be duplicated"],"metadata":{"id":"BGqBDqjcX0j2"}},{"cell_type":"markdown","source":["## Initialize/Create a dictionary with following entry\n","{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}"],"metadata":{"id":"2udDQtmBAYEM"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"P7Pbe7NkAO75"},"outputs":[],"source":["d= { 8 : 'cppp',\n"," 3: 'Python', 2: 'Java', 1: 'Ruby',\n"," 11: 'Cplus',\n"," 4: 'Scala'}"]},{"cell_type":"code","source":["# sorting the keys_list\n","keys_list = list(d.keys())\n","print(keys_list)\n","#keys_list.sort()\n","#print(keys_list)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":235},"id":"5FkhZNBLAgqT","executionInfo":{"status":"error","timestamp":1665974951847,"user_tz":-330,"elapsed":7,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"outputId":"929e731b-3151-4c95-8b85-443670d2ede4"},"execution_count":1,"outputs":[{"output_type":"error","ename":"NameError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# sorting the keys_list\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mkeys_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mkeys\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkeys_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;31m#keys_list.sort()\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;31m#print(keys_list)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mNameError\u001b[0m: name 'd' is not defined"]}]},{"cell_type":"code","source":["# sorting the values list\n","values_list = list(d.values())\n","print(values_list)\n","values_list.sort()\n","print(values_list)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"GLg41enlAy48","executionInfo":{"status":"ok","timestamp":1665969128312,"user_tz":-330,"elapsed":30,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f1b1e1d0-0e13-4ba1-ae9c-e863b05ae9f3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["['cppp', 'Python', 'Java', 'Ruby', 'Cplus', 'Scala']\n","['Cplus', 'Java', 'Python', 'Ruby', 'Scala', 'cppp']\n"]}]},{"cell_type":"code","source":["# custom sorting of the values_list based inline function - `lambda`\n","values_list.sort(key=lambda item: len(item))\n","print(values_list)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"WYPxwIgYB4p9","executionInfo":{"status":"ok","timestamp":1665969128313,"user_tz":-330,"elapsed":28,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"3e6fd217-6d3b-4d91-a314-ec80270d249d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["['Java', 'Ruby', 'cppp', 'Cplus', 'Scala', 'Python']\n"]}]},{"cell_type":"code","source":["# user defined function\n","def my_add(x, y):\n"," z = x+y\n"," return z"],"metadata":{"id":"082eCRe8Cajc"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# calling of user defined function my_add\n","t = my_add(2,3)\n","print(t)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"jByz_TVkClGE","executionInfo":{"status":"ok","timestamp":1665969128315,"user_tz":-330,"elapsed":25,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b88f598a-b2c2-44fd-97cd-302503b906f8"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["5\n"]}]},{"cell_type":"code","source":["# sorting the dictionary items\n","items_list = list(d.items())\n","print(items_list)\n","items_list.sort()\n","print(items_list)\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"bN3gnxChBkos","executionInfo":{"status":"ok","timestamp":1665969128316,"user_tz":-330,"elapsed":23,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"eab7b599-6532-4811-cf5a-8c48140ead7b"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["[(8, 'cppp'), (3, 'Python'), (2, 'Java'), (1, 'Ruby'), (11, 'Cplus'), (4, 'Scala')]\n","[(1, 'Ruby'), (2, 'Java'), (3, 'Python'), (4, 'Scala'), (8, 'cppp'), (11, 'Cplus')]\n"]}]},{"cell_type":"code","source":["# custom sort on the values of dictionary items\n","items_list.sort(key = lambda item : len(item[1]), reverse=True)\n","print(items_list)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"jAhXr852HkFk","executionInfo":{"status":"ok","timestamp":1665969128317,"user_tz":-330,"elapsed":22,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"337668bc-a70a-4ba3-9a72-af1e31ae46a3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["[(3, 'Python'), (4, 'Scala'), (11, 'Cplus'), (1, 'Ruby'), (2, 'Java'), (8, 'cppp')]\n"]}]},{"cell_type":"markdown","source":["## acessing the value in dictionary\n","- using key\n","- using .get method"],"metadata":{"id":"ihhzwoHUfewi"}},{"cell_type":"code","source":["print(d[8])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"VO7I-q85fuCp","executionInfo":{"status":"ok","timestamp":1665969128317,"user_tz":-330,"elapsed":19,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b0e93d08-2d6d-41b1-d0ad-86d2e05c70b4"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["cppp\n"]}]},{"cell_type":"code","source":["# what if key is not present in the dictionary - `KeyError`\n","print(d[10])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":187},"id":"qHKBujUTf6R-","executionInfo":{"status":"error","timestamp":1665969177601,"user_tz":-330,"elapsed":8,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"87699b53-b912-4410-fae0-02bed10b6d12"},"execution_count":null,"outputs":[{"output_type":"error","ename":"KeyError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# what if key is not present in the dictionary - `KeyError`\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mKeyError\u001b[0m: 10"]}]},{"cell_type":"code","source":["print(d.get(10, 'Element Not Found!'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"mukow5ThgE5B","executionInfo":{"status":"ok","timestamp":1665969230061,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"e1008bc1-aed7-478b-afe8-72505af02b10"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Element Not Found!\n"]}]},{"cell_type":"code","source":["print(d.get(10, -999999999))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"7MaGIslzgN0v","executionInfo":{"status":"ok","timestamp":1665969227694,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"51b28728-5a9b-4ad9-c795-16b1c6e6668d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["-999999999\n"]}]},{"cell_type":"code","source":["print(d.get(10,))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"5k5lZpVugSM_","executionInfo":{"status":"ok","timestamp":1665969241727,"user_tz":-330,"elapsed":399,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"46dbf5dc-312a-412c-a32f-11b6787dc7f2"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["None\n"]}]},{"cell_type":"markdown","source":["## deleting element from dictionary usig `del` statement"],"metadata":{"id":"cL0rAuKtgVPC"}},{"cell_type":"code","source":["del d[8]"],"metadata":{"id":"s22slWcOgbQ-"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["print(d)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"GpW-t_lSgeY_","executionInfo":{"status":"ok","timestamp":1665969290030,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"c127b930-9800-4136-b581-a768885ab2bd"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'Scala'}\n"]}]},{"cell_type":"code","source":["print(d[8])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":169},"id":"ZXzCpU6eggc2","executionInfo":{"status":"error","timestamp":1665969300742,"user_tz":-330,"elapsed":339,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8155b774-5497-4059-d5db-3698c0ce355a"},"execution_count":null,"outputs":[{"output_type":"error","ename":"KeyError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m8\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mKeyError\u001b[0m: 8"]}]},{"cell_type":"code","source":["print(d.get(8,'Value not present'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"aw_uaFmvgiyH","executionInfo":{"status":"ok","timestamp":1665969330525,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"395b29d7-f9ce-4cd5-8267-09a109bdfddf"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Value not present\n"]}]},{"cell_type":"code","source":["## Adding new key-value pair"],"metadata":{"id":"5fSGkaTJhG1p"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["print(d)\n","d[12] = 'Matlab'\n","print(d)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Ny7bxGOFhKIG","executionInfo":{"status":"ok","timestamp":1665969539478,"user_tz":-330,"elapsed":370,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"a8911074-ae14-4d38-ed2f-3c3424735344"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'Scala', 8: 'cpp'}\n","{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'Scala', 8: 'cpp', 12: 'Matlab'}\n"]}]},{"cell_type":"code","source":["d[10] = 'R'\n","print(d)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"tEyr0aWshdKo","executionInfo":{"status":"ok","timestamp":1665969564167,"user_tz":-330,"elapsed":372,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8013c467-7685-4ac4-a0af-1f544ef89e10"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'Scala', 8: 'cpp', 12: 'Matlab', 10: 'R'}\n"]}]},{"cell_type":"markdown","source":["### changing/reassigning the key-value pair"],"metadata":{"id":"KDcLL6UGhzQB"}},{"cell_type":"code","source":["print(d)\n","d[4] = 'javascript'\n","print(d)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kTpqvhNjhpxn","executionInfo":{"status":"ok","timestamp":1665969656103,"user_tz":-330,"elapsed":351,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"171a641d-d35d-4568-8dba-01b7dcc0d0c0"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'javascript', 8: 'cpp', 12: 'Matlab', 10: 'R'}\n","{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'javascript', 8: 'cpp', 12: 'Matlab', 10: 'R'}\n"]}]},{"cell_type":"markdown","source":["### Dictionary with same value in two different key"],"metadata":{"id":"_jW0ZVXeh7jI"}},{"cell_type":"code","source":["print(d)\n","d[10]= 'Matlab'\n","print(d)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"BIIULFdWiB3q","executionInfo":{"status":"ok","timestamp":1665969964353,"user_tz":-330,"elapsed":385,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"feec4dae-c2ef-4196-fe9a-75cad3fa4448"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'javascript', 8: 'cpp', 12: 'Matlab', 10: 'Matlab'}\n","{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'javascript', 8: 'cpp', 12: 'Matlab', 10: 'Matlab'}\n"]}]},{"cell_type":"markdown","source":["## iterating over dictionary"],"metadata":{"id":"G5zyl2v7iIlA"}},{"cell_type":"markdown","source":[],"metadata":{"id":"ZrUflwqciMZ_"}},{"cell_type":"code","source":["print(d)\n","for key, value in d.items():\n"," print(f'key={key}, value={value}')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"3UK7m72Ii9aY","executionInfo":{"status":"ok","timestamp":1665971513343,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"e3792d49-58ca-4d2e-9f48-4fce1f8fc9a8"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{3: 'Python', 2: 'Java', 1: 'Ruby', 11: 'Cplus', 4: 'javascript', 8: 'cpp', 12: 'Matlab', 10: 'Matlab'}\n","key=3, value=Python\n","key=2, value=Java\n","key=1, value=Ruby\n","key=11, value=Cplus\n","key=4, value=javascript\n","key=8, value=cpp\n","key=12, value=Matlab\n","key=10, value=Matlab\n"]}]},{"cell_type":"code","source":[],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"UMioIiIao_87","executionInfo":{"status":"ok","timestamp":1665971554567,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"526559f9-df9f-4edd-9256-0affcd36694f"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["key=3, value=Python\n","key=2, value=Java\n","key=1, value=Ruby\n","key=11, value=Cplus\n","key=4, value=javascript\n","key=8, value=cpp\n","key=12, value=Matlab\n","key=10, value=Matlab\n"]}]},{"cell_type":"code","source":["for key in d.keys():\n"," print(f'key={key}, value={d[key]}')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kfjskiHXpY0V","executionInfo":{"status":"ok","timestamp":1665971636835,"user_tz":-330,"elapsed":344,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"e6b68ba9-dc65-48cd-a596-9ac055594ab3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["key=3, value=Python\n","key=2, value=Java\n","key=1, value=Ruby\n","key=11, value=Cplus\n","key=4, value=javascript\n","key=8, value=cpp\n","key=12, value=Matlab\n","key=10, value=Matlab\n"]}]},{"cell_type":"code","source":["# accessing elements of dictionary using sorted keys\n","for key in sorted(d.keys()):\n"," print(f'key={key}, value={d[key]}')\n","\n","## What is the difference between sort and sorted ?"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"uQAzhBA7jBWA","executionInfo":{"status":"ok","timestamp":1665971684086,"user_tz":-330,"elapsed":341,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"e049985a-be01-4294-8c6f-69340a742be3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["key=1, value=Ruby\n","key=2, value=Java\n","key=3, value=Python\n","key=4, value=javascript\n","key=8, value=cpp\n","key=10, value=Matlab\n","key=11, value=Cplus\n","key=12, value=Matlab\n"]}]},{"cell_type":"markdown","source":["## Given a list of top-3 popular llanguage of 2022\n","- popular_lang = ['Python', 'javascript', 'Java']\n","- Loop throught dictionary and check whether than language present in the value is ppoular language or not?\n","- suppose the language is Python and it is popular language\n","-- print - Python is popular language\n","- otherwise\n","-- print - Python is not popular language"],"metadata":{"id":"VH0095wvpx8s"}},{"cell_type":"markdown","source":["### After python 3.7 dictionary items are ordered in the order they are added to the dictionary.*italicized text*"],"metadata":{"id":"QAgQ6HtyqeUj"}},{"cell_type":"markdown","source":["## Nested dictionary\n","- list inside a dictionary\n","- dictionary inside a dictionary\n","- dictionary inside a list"],"metadata":{"id":"y9bOobxbs_9v"}},{"cell_type":"code","source":[],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":133},"id":"puxRle1Cqedy","executionInfo":{"status":"error","timestamp":1665972561616,"user_tz":-330,"elapsed":399,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"1bf7a1e5-63b0-418e-e257-ab347ce98952"},"execution_count":null,"outputs":[{"output_type":"error","ename":"SyntaxError","evalue":"ignored","traceback":["\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m - list inside a dictionary\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"]}]}]} -------------------------------------------------------------------------------- /Module_4_Collections/lab_09_sets.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Sets : unordered collection data type that is \n","- iterable\n","- heterogenous\n","- mutable\n","- no duplicate elements\n","- non subscriptable\n","\n","## Advantage:\n","- it has a highly optimized method for checking whether a specific element is contained in the set.\n","\n","## Methods\n","- add value/values - .`add`(), .`extend`()\n","- check value present is set - `in` keyword\n","- delete values from set - .`remove`(), .`discard`(), .`pop`(), .`clear`()"],"metadata":{"id":"wX2d9mqwfw1r"}},{"cell_type":"code","source":["set_a = {'r', 'q', 'st'}\n","print(set_a)\n","set_b = set([1, 'C', 'E', 'A'])\n","print(set_b)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"BHG8xLBLgYO_","executionInfo":{"status":"ok","timestamp":1665978839920,"user_tz":-330,"elapsed":1298,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"outputId":"33321fbd-4ce5-4046-f211-6fb69cbe2c11"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{'st', 'r', 'q'}\n","{1, 'A', 'C', 'E'}\n"]}]},{"cell_type":"code","source":["print(set_a[1])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":165},"id":"KK7kVX1xgpmc","executionInfo":{"status":"error","timestamp":1665978840305,"user_tz":-330,"elapsed":11,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"outputId":"91d3aaf9-c5fb-4e88-cb5a-a33bd88bc42e"},"execution_count":null,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mset_a\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'set' object is not subscriptable"]}]},{"cell_type":"markdown","source":["## Adding values in a set\n","- .add( )\n","- .extend( )"],"metadata":{"id":"5p760wNV7XT8"}},{"cell_type":"code","source":["# typecasting list to set\n","myset = set([\"a\", \"b\", \"c\"])\n","print(myset)\n"," \n","# Adding element to the set\n","myset.add(\"d\")\n","print(myset)"],"metadata":{"id":"sekuhoo17gbU","executionInfo":{"status":"ok","timestamp":1665978846465,"user_tz":-330,"elapsed":1022,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"4c096bd3-440d-436f-8f0c-0f49cf5de494"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{'a', 'c', 'b'}\n","{'d', 'a', 'c', 'b'}\n"]}]},{"cell_type":"code","source":["# Creating a empty Set\n","set1 = set()\n","print(\"Initial blank Set: \")\n","print(set1)\n"," \n","# Adding element and tuple to the Set\n","set1.add(8)\n","set1.add(9)\n","set1.add((6, 7))\n","print(\"\\nSet after Addition of Three elements: \")\n","print(set1)"],"metadata":{"id":"TBEDqu_57rvr","executionInfo":{"status":"ok","timestamp":1665978850015,"user_tz":-330,"elapsed":382,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"09ad84c7-f5ff-46f2-fb99-cce86b534716"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Initial blank Set: \n","set()\n","\n","Set after Addition of Three elements: \n","{8, 9, (6, 7)}\n"]}]},{"cell_type":"code","source":["# Adding elements to the Set\n","# using Iterator\n","for i in range(1, 6):\n"," set1.add(i)\n","print(\"\\nSet after Addition of elements from 1-5: \")\n","print(set1)"],"metadata":{"id":"nZsd0y5U731l","executionInfo":{"status":"ok","timestamp":1665978858968,"user_tz":-330,"elapsed":4,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"53cd8b17-4540-4c96-c471-de599757d424"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","Set after Addition of elements from 1-5: \n","{1, 2, 3, (6, 7), 4, 5, 8, 9}\n"]}]},{"cell_type":"code","source":["# Addition of elements to the Set\n","# using Update function\n","print(set1)\n","set1.update([20, 30])\n","print(\"\\nSet after Addition of elements using Update: \")\n","print(set1)"],"metadata":{"id":"0h1ljMjF7-Uj","executionInfo":{"status":"ok","timestamp":1665979046917,"user_tz":-330,"elapsed":1202,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"10095f7c-7b9d-49c3-b3f0-d2dc6e9c1c3c"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{1, 2, 3, (6, 7), 4, 5, 8, 9}\n","\n","Set after Addition of elements using Update: \n","{1, 2, 3, (6, 7), 4, 5, 8, 9, 20, 30}\n"]}]},{"cell_type":"markdown","source":["## Checking whether values present in a set or not?\n","- `in`\n","- Initialize a set of your favorate integers.\n","- Take an integer input (num) from user and check\n","- if the num is one among your favourate integer "],"metadata":{"id":"ivzVMR5D99Mu"}},{"cell_type":"code","source":[],"metadata":{"id":"SqXAi2l4-eY8"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["## Delete an item/items from set\n","- .remove()- a KeyError arises if the element doesn’t exist in the set.\n","- .discard() - if the element doesn’t exist in the set, it remains unchanged.\n","- .pop() - Remove and return an arbitrary set element.\n"," Raises `KeyError` if the set is empty.\n","- .clear()"],"metadata":{"id":"TJyjNWsQ-fEM"}},{"cell_type":"code","source":["# Creating a Set\n","set1 = set([1, 2, 3, 4, 5, 6,\n"," 7, 8, 9, 10, 11, 12])\n","print(\"Initial Set: \")\n","print(set1)\n"," \n","# Removing elements from Set - using Remove() method\n","set1.remove(5)\n","set1.remove(6)\n","print(\"\\nSet after Removal of two elements: \")\n","print(set1)"],"metadata":{"id":"t67r-jVZ_du7","executionInfo":{"status":"ok","timestamp":1665979125870,"user_tz":-330,"elapsed":356,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"2de3ff3a-1d6c-4ebf-f77c-308d13b644af"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Initial Set: \n","{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}\n","\n","Set after Removal of two elements: \n","{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}\n"]}]},{"cell_type":"code","source":["# Removing elements from Set\n","# using Discard() method\n","print(set1)\n","set1.discard(8)\n","set1.discard(9)\n","print(\"\\nSet after Discarding two elements: \")\n","print(set1)"],"metadata":{"id":"4B9ZeQhR_hYa","executionInfo":{"status":"ok","timestamp":1665979310455,"user_tz":-330,"elapsed":6,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"6b63bd39-71b9-4cd8-eb24-1a547ab4b7a2"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}\n","\n","Set after Discarding two elements: \n","{1, 2, 3, 4, 7, 10, 11, 12}\n"]}]},{"cell_type":"code","source":["# Removing elements from Set\n","# using Discard() method\n","print(set1)\n","set1.discard(22)\n","set1.discard(31)\n","print(\"\\nSet after Discarding two elements: \")\n","print(set1)"],"metadata":{"id":"8q8BlMQa_qhy","executionInfo":{"status":"ok","timestamp":1665979323551,"user_tz":-330,"elapsed":362,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"28675943-7bdb-4262-dd16-5d534fce68b5"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{1, 2, 3, 4, 7, 10, 11, 12}\n","\n","Set after Discarding two elements: \n","{1, 2, 3, 4, 7, 10, 11, 12}\n"]}]},{"cell_type":"code","source":["help(set1.pop)"],"metadata":{"id":"LkVxQzUQ_4Zc","executionInfo":{"status":"ok","timestamp":1665979327859,"user_tz":-330,"elapsed":402,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"54c12e73-c242-4b44-b078-875bb82a9143"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Help on built-in function pop:\n","\n","pop(...) method of builtins.set instance\n"," Remove and return an arbitrary set element.\n"," Raises KeyError if the set is empty.\n","\n"]}]},{"cell_type":"code","source":["set1 = set([1, 2, 3, 4, 5, 6,\n"," 7, 8, 9, 10, 11, 12])\n","for i in range(5):\n"," print(set1)\n"," x = set1.pop()\n"," print(x)"],"metadata":{"id":"1fXlIdyXANvs","executionInfo":{"status":"ok","timestamp":1665979332061,"user_tz":-330,"elapsed":4,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"424151bb-c250-4cf1-98cf-572768dfa8a8"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}\n","1\n","{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}\n","2\n","{3, 4, 5, 6, 7, 8, 9, 10, 11, 12}\n","3\n","{4, 5, 6, 7, 8, 9, 10, 11, 12}\n","4\n","{5, 6, 7, 8, 9, 10, 11, 12}\n","5\n"]}]},{"cell_type":"markdown","source":["## Other methods\n","- union\n","- intersection\n","- difference"],"metadata":{"id":"YrlwtSLFAzuy"}},{"cell_type":"markdown","source":["### Union"],"metadata":{"id":"5xW-zqdBBqaC"}},{"cell_type":"code","source":["people = {\"Jay\", \"Idrish\", \"Archil\"}\n","vampires = {\"Karan\", \"Arjun\"}\n","dracula = {\"Deepanshu\", \"Raju\"}"],"metadata":{"id":"BkPswlKNA_fa","executionInfo":{"status":"ok","timestamp":1666159016769,"user_tz":-330,"elapsed":12,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":1,"outputs":[]},{"cell_type":"code","source":["# Union using union() function\n","population = people.union(vampires)\n"," \n","print(\"Union using union() function\")\n","print(population)"],"metadata":{"id":"B0O1_RmcBFsL","executionInfo":{"status":"ok","timestamp":1666159016772,"user_tz":-330,"elapsed":12,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"8d141ff8-331c-4f8c-a1ca-70aaf476e700"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["Union using union() function\n","{'Arjun', 'Karan', 'Idrish', 'Jay', 'Archil'}\n"]}]},{"cell_type":"code","source":["# Union using \"|\" operator\n","population = people|dracula\n"," \n","print(\"\\nUnion using '|' operator\")\n","print(population)"],"metadata":{"id":"ZkQf4-sdBHxY","executionInfo":{"status":"ok","timestamp":1666159028396,"user_tz":-330,"elapsed":411,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"0b31abcb-e361-4405-c397-e131a1891eec"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","Union using '|' operator\n","{'Deepanshu', 'Raju', 'Idrish', 'Jay', 'Archil'}\n"]}]},{"cell_type":"markdown","source":["### intersection"],"metadata":{"id":"yZTBgQ5SBttB"}},{"cell_type":"code","source":["set1 = set(range(5,16, 2))\n","set2 = set(range(4,18,3))\n","print(set1)\n","print(set2)"],"metadata":{"id":"V9IpIe5XBvmR","executionInfo":{"status":"ok","timestamp":1665979359292,"user_tz":-330,"elapsed":2,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"cb1250bd-6001-4810-b18a-2033d6ea8d92"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{5, 7, 9, 11, 13, 15}\n","{4, 7, 10, 13, 16}\n"]}]},{"cell_type":"code","source":["# Intersection using intersection() function\n","set3 = set1.intersection(set2)\n","print(\"Intersection using intersection() function\")\n","print(set3)"],"metadata":{"id":"jPiyJ9piAtRa","executionInfo":{"status":"ok","timestamp":1665979361616,"user_tz":-330,"elapsed":3,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"b814a9e0-976f-42d9-8a0b-b8e9ef5cc854"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Intersection using intersection() function\n","{13, 7}\n"]}]},{"cell_type":"code","source":["# Intersection using \"&\" operator\n","set3 = set1 & set2\n","print(\"\\nIntersection using '&' operator\")\n","print(set3)"],"metadata":{"id":"cmg97h7MCL1F"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["### difference"],"metadata":{"id":"mFq2sAZCCTn6"}},{"cell_type":"code","source":["# using difference() function\n","print(set1)\n","print(set2)\n","set3 = set1.difference(set2)\n","print(set3)"],"metadata":{"id":"Jir7EiICCVZB","executionInfo":{"status":"ok","timestamp":1665979364198,"user_tz":-330,"elapsed":4,"user":{"displayName":"Anandita Iyer","userId":"06887648733315468255"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"31aa1079-ce66-4b96-84ce-54de5fa3a434"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["{5, 7, 9, 11, 13, 15}\n","{4, 7, 10, 13, 16}\n","{9, 11, 5, 15}\n"]}]},{"cell_type":"code","source":["# Difference of two sets using '-' operator\n","set3 = set1 - set2\n","print(set3)"],"metadata":{"id":"_N8RVFlSCZzD"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["#### More operations on sets in the link: https://www.geeksforgeeks.org/sets-in-python/"],"metadata":{"id":"mB_9icTPCjI5"}},{"cell_type":"markdown","source":[],"metadata":{"id":"aNj1BdZa-Est"}},{"cell_type":"code","source":["help(set_a)"],"metadata":{"id":"kQFt--Obgw_L"},"execution_count":null,"outputs":[]}]} -------------------------------------------------------------------------------- /Module_4_Collections/lab_09_tuple.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"1JREJ2xKrojyJqIG8n3qkBUYjcreBX63H","timestamp":1665602039070}],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Tuples\n","- a collection of Python objects like list\n","- can contain heterogenous objects (data types)\n","- is immutable"],"metadata":{"id":"FWZFoSPEZnnZ"}},{"cell_type":"markdown","source":["## Intialize a tuple"],"metadata":{"id":"iwY5Gc3GZrRJ"}},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"-OjcafDIZA_4","outputId":"98e8d439-5355-4807-9c8d-9673bb95dd21"},"outputs":[{"output_type":"stream","name":"stdout","text":["(1, 'ram', 64.89, None, False)\n"]}],"source":["# tuple as hetegeneous element\n","my_tuple = (1, 'ram', 64.89, None, False)\n","print(my_tuple)\n"]},{"cell_type":"code","source":["# tuple as homogenous element\n","my_tuple = (1, 19, 48, 64, 97)\n","print(my_tuple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"lvKoTDaOaBKb","outputId":"3dcd335c-1cd1-498b-b6cc-6af5af13fd23"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["(1, 19, 48, 64, 97)\n"]}]},{"cell_type":"code","source":["# tuple as a collection of tuple\n","my_tuple = ( (47.89, 32.64) ,(48.57, 64.09) , (97.87, 14.80) )\n","print(my_tuple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"pIIYEreGaGRR","outputId":"4386388d-2a6c-4de5-f1c0-54ff71e38403"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["((47.89, 32.64), (48.57, 64.09), (97.87, 14.8))\n"]}]},{"cell_type":"code","source":["my_tuple = ( [47.89, 32.64] , [48.57, 64.09] , [97.87, 14.80], [20.45, 93.67] )\n","print(my_tuple)\n","print(id(my_tuple))\n","print(id(my_tuple[1]))\n","my_tuple[1].append(34)\n","print(id(my_tuple[1]))\n","print(my_tuple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"MsCPYBdpqE4-","outputId":"b56a46cf-1cfe-4e0c-ac00-39de3bc53832"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["([47.89, 32.64], [48.57, 64.09], [97.87, 14.8], [20.45, 93.67])\n","139857658686256\n","139857524071152\n","139857524071152\n","([47.89, 32.64], [48.57, 64.09, 34], [97.87, 14.8], [20.45, 93.67])\n"]}]},{"cell_type":"code","source":["# tuple as a collection of list"],"metadata":{"id":"c1Hzj0xkabDJ"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["## indexing a tuple\n","- similar to list"],"metadata":{"id":"XTCG0gQUae5x"}},{"cell_type":"code","source":["print(my_tuple)\n","print(my_tuple[0])\n","print(my_tuple[-1])\n","print(my_tuple[1][1])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"yXCa_0plaieh","outputId":"25273993-5fc1-4471-f9b2-df656960e321"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["([47.89, 32.64], [48.57, 64.09], [97.87, 14.8], [20.45, 93.67])\n","[47.89, 32.64]\n","[20.45, 93.67]\n","64.09\n"]}]},{"cell_type":"code","source":["# slicing to pick up second and third entry of tuple\n","print(my_tuple[1:3])\n","print(my_tuple[1:4:2])\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"pVaDAsb1ajDN","outputId":"3b5099bc-3cfb-4452-9442-1920b8f651ec"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["('ram', 64.89)\n","('ram', None)\n"]}]},{"cell_type":"markdown","source":["## Imutable property"],"metadata":{"id":"JHnKhjlRajay"}},{"cell_type":"code","source":["my_tuple = (1, 19, 48, 64, 97)\n","print(my_tuple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"1lh-sCMTatfb","outputId":"a52ab135-0f4a-47ab-a52b-cc35c83a900f"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["(1, 19, 48, 64, 97)\n"]}]},{"cell_type":"code","source":["my_tuple[1] = 24"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":168},"id":"hkAIaOmwatn5","outputId":"4a18079e-6ab5-4597-d48c-0070cd6c1d0c"},"execution_count":null,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m24\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"]}]},{"cell_type":"code","source":["del my_tuple[1]"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":168},"id":"zcTqIr55bALs","outputId":"ab937410-d527-40d8-8af1-6715e3bc419e"},"execution_count":null,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mdel\u001b[0m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'tuple' object doesn't support item deletion"]}]},{"cell_type":"code","source":["my_tuple.append(27)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":168},"id":"aRk0GpVWbEox","outputId":"8ce2489b-0b1d-444b-b7f7-bb898976a89a"},"execution_count":null,"outputs":[{"output_type":"error","ename":"AttributeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m27\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'append'"]}]},{"cell_type":"code","source":["my_tuple.insert(1, 27)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":168},"id":"a0DQtp-KbIpS","outputId":"422b6d95-ed78-4f50-952e-f0e2ad7df58e"},"execution_count":null,"outputs":[{"output_type":"error","ename":"AttributeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minsert\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m27\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'insert'"]}]},{"cell_type":"code","source":["print(my_tuple)\n","my_tuple = (21, 19)\n","print(my_tuple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"-kyRQhsbtKLr","outputId":"606e7cd2-96b2-4109-bad3-f4863924bc03"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["(1, 19, 48, 64, 97)\n","(21, 19)\n"]}]},{"cell_type":"markdown","source":["## Operation on tuple\n","- insertion/deletion - not allowed\n","- updating a part of value - not allowed\n","- Searching/Conting an element - .index, count"],"metadata":{"id":"Mo64jZKTauBL"}},{"cell_type":"code","source":["help(my_tuple)"],"metadata":{"id":"YxeLA2aXuQBz","outputId":"82babda1-452f-45c6-e2fe-0b7e678dec68","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Help on tuple object:\n","\n","class tuple(object)\n"," | tuple(iterable=(), /)\n"," | \n"," | Built-in immutable sequence.\n"," | \n"," | If no argument is given, the constructor returns an empty tuple.\n"," | If iterable is specified the tuple is initialized from iterable's items.\n"," | \n"," | If the argument is a tuple, the return value is the same object.\n"," | \n"," | Methods defined here:\n"," | \n"," | __add__(self, value, /)\n"," | Return self+value.\n"," | \n"," | __contains__(self, key, /)\n"," | Return key in self.\n"," | \n"," | __eq__(self, value, /)\n"," | Return self==value.\n"," | \n"," | __ge__(self, value, /)\n"," | Return self>=value.\n"," | \n"," | __getattribute__(self, name, /)\n"," | Return getattr(self, name).\n"," | \n"," | __getitem__(self, key, /)\n"," | Return self[key].\n"," | \n"," | __getnewargs__(self, /)\n"," | \n"," | __gt__(self, value, /)\n"," | Return self>value.\n"," | \n"," | __hash__(self, /)\n"," | Return hash(self).\n"," | \n"," | __iter__(self, /)\n"," | Implement iter(self).\n"," | \n"," | __le__(self, value, /)\n"," | Return self<=value.\n"," | \n"," | __len__(self, /)\n"," | Return len(self).\n"," | \n"," | __lt__(self, value, /)\n"," | Return self\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdays\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'Deepawali'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"]}]},{"cell_type":"code","source":["days += 'Deepawali'"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":168},"id":"XG3_pjXRaD3i","executionInfo":{"status":"error","timestamp":1666353514662,"user_tz":-330,"elapsed":16,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"bdd6ace9-0e8e-487c-e0bb-7c7c9ef9dd76"},"execution_count":24,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdays\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;34m'Deepawali'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: can only concatenate tuple (not \"str\") to tuple"]}]},{"cell_type":"code","source":["### String\n","st = 'HappY Deepawali'\n","st[:5] = 'happy'"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":203},"id":"4HBTxlNZaP0T","executionInfo":{"status":"error","timestamp":1666353577911,"user_tz":-330,"elapsed":18,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"245990f3-4eee-40d6-b286-843eb05dae15"},"execution_count":25,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m### String\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mst\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'HappY Deepawali'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mst\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'happy'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"]}]}]} -------------------------------------------------------------------------------- /Module_5_Strings_and_Regular_Expressions/lab_10_string_practice.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"collapsed_sections":[],"authorship_tag":"ABX9TyM68TB75tytY5sRtoinLqgx"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# String practice problems"],"metadata":{"id":"UDwu2Kk0naRi"}},{"cell_type":"markdown","source":["## Q1. WAF to count the occurrence of every character in a string.\n"," a. Find the most frequent character\n"," \n"," b. Find the least frequent character.\n"],"metadata":{"id":"XP1o2xoKnhPK"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"3JHEkywEnWwr"},"outputs":[],"source":["def count_char_freq(st):\n"," char_dict= {}\n"," for ch in st:\n"," if ch not in char_dict:\n"," char_dict[ch] = 0\n"," char_dict[ch] += 1\n"," return char_dict\n"]},{"cell_type":"code","source":["my_st = 'I am learning python at SJT 515 Lab'\n","char_dict_new = count_char_freq(my_st)\n","print(my_st)\n","print(char_dict_new)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"jajPufsMoEaM","executionInfo":{"status":"ok","timestamp":1666357679630,"user_tz":-330,"elapsed":421,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d97a12f8-d15c-4628-9f06-8e79c007b8d4"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["I am learning python at SJT 515 Lab\n","{'I': 1, ' ': 7, 'a': 4, 'm': 1, 'l': 1, 'e': 1, 'r': 1, 'n': 3, 'i': 1, 'g': 1, 'p': 1, 'y': 1, 't': 2, 'h': 1, 'o': 1, 'S': 1, 'J': 1, 'T': 1, '5': 2, '1': 1, 'L': 1, 'b': 1}\n"]}]},{"cell_type":"code","source":["max(char_dict_new.items(), key=lambda x: x[1] )[0]"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":35},"id":"FA4dd65fqtni","executionInfo":{"status":"ok","timestamp":1666358000277,"user_tz":-330,"elapsed":16,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"11783345-70c7-4ebb-9dc6-c69c305463d1"},"execution_count":null,"outputs":[{"output_type":"execute_result","data":{"text/plain":["' '"],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":9}]},{"cell_type":"code","source":["sorted(char_dict_new.items(), key=lambda x: x[1], reverse=True)[0]"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"-yUoA0JHrUn7","executionInfo":{"status":"ok","timestamp":1666358023593,"user_tz":-330,"elapsed":866,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"fedb36e3-f712-4fdb-ffcb-0bb5a0d28d3d"},"execution_count":null,"outputs":[{"output_type":"execute_result","data":{"text/plain":["(' ', 7)"]},"metadata":{},"execution_count":11}]},{"cell_type":"code","source":["min(char_dict_new.items(), key=lambda x: x[1] )"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"wAeFa9slrQnS","executionInfo":{"status":"ok","timestamp":1666357993995,"user_tz":-330,"elapsed":675,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8b6a5194-f991-4606-ec1c-2377be8e5beb"},"execution_count":null,"outputs":[{"output_type":"execute_result","data":{"text/plain":["('I', 1)"]},"metadata":{},"execution_count":8}]},{"cell_type":"markdown","source":["## Find the number of words in a string considering SPACE as word separator."],"metadata":{"id":"f0FkMPnxpsUP"}},{"cell_type":"code","source":["def count_number_of_words(st):\n"," word_list = st.strip().split(' ')\n"," print(word_list)\n"," return word_list"],"metadata":{"id":"xnQJ8G-EqOTp"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["my_st = ' \\n I am learning python at SJT 515 Lab \\t'\n","words_list = count_number_of_words(my_st)\n","print(words_list)\n","print(len(words_list))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"PTDWMjU9uNRZ","executionInfo":{"status":"ok","timestamp":1666359147523,"user_tz":-330,"elapsed":3,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"0cfaad54-62d1-4620-bdd3-2d656c16fde9"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["['I', 'am', 'learning', 'python', 'at', 'SJT', '515', 'Lab']\n","['I', 'am', 'learning', 'python', 'at', 'SJT', '515', 'Lab']\n","8\n"]}]},{"cell_type":"code","source":["print(my_st[4:8])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kuXhe4eVvw1i","executionInfo":{"status":"ok","timestamp":1666359178596,"user_tz":-330,"elapsed":634,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"ee74b516-5e7f-4af7-a5db-2b46583d6006"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["I am\n"]}]},{"cell_type":"markdown","source":["## String Formatting"],"metadata":{"id":"YhWHufBvwODp"}},{"cell_type":"markdown","source":["#### left, center, and right alignment"],"metadata":{"id":"Bu4nL4uFp4UQ"}},{"cell_type":"code","source":["String=\"Python\"\n","print(\"Left,centre and right alignment by formatting:\")\n","print(\"|{:<15}|{:^15}|{:>15}|\".format(String,'is','fun'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vRWbobD2wQLQ","executionInfo":{"status":"ok","timestamp":1666359299925,"user_tz":-330,"elapsed":469,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"04a03080-7d78-4857-c7e1-edd51842aba3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Left,centre and right alignment by formatting:\n","|Python | is | fun|\n"]}]},{"cell_type":"markdown","source":["#### decimal to binary, floating point representation"],"metadata":{"id":"1uyK7pCDp_Cx"}},{"cell_type":"code","source":["print(\"Binary representation of 16 is: {0:b}\".format(10))\n","print(\"Exponent form of of 13.56 is: {0:e}\".format(13.56))\n","print(\"Rounding of 1/3 to 3 decimal places: {0:.3f}\".format(1/3))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"uRFLuDEzwbI3","executionInfo":{"status":"ok","timestamp":1666359345144,"user_tz":-330,"elapsed":945,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"43e8be13-6cff-493a-bf60-4d20f5569bd7"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Binary representation of 16 is: 1010\n","Exponent form of of 13.56 is: 1.356000e+01\n","Rounding of 1/3 to 3 decimal places: 0.333\n"]}]},{"cell_type":"markdown","source":["## Function to check type of character:\n","- isdigit()\n","- isalpha()\n","- isspace() "],"metadata":{"id":"l1lW80j5xURy"}},{"cell_type":"code","source":["var1='abc'\n","print(var1.isalpha())\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"-yhvVYtexN3J","executionInfo":{"status":"ok","timestamp":1666359604163,"user_tz":-330,"elapsed":438,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"16e45d58-5e66-4e7f-8809-2513576b4767"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n"]}]},{"cell_type":"code","source":["var2='aei4'\n","print(var2.isalpha())\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"aOvtrWW1xcHZ","executionInfo":{"status":"ok","timestamp":1666359728711,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"ff667042-5aee-481e-ec28-cc8fef550ce7"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["False\n"]}]},{"cell_type":"code","source":["var3='234'\n","print(var3.isdigit())\n","print(var2.isdigit())\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Rs8ogBHzxgZq","executionInfo":{"status":"ok","timestamp":1666359744727,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"10950f4c-efa9-4c24-f6e3-74a5685d9d75"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n","False\n"]}]},{"cell_type":"code","source":["var4=\" \"\n","print(var4.isspace())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"QkquKbCLxlaQ","executionInfo":{"status":"ok","timestamp":1666359653137,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f456f9d8-94e3-4366-ffcc-c42033a54e0e"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n"]}]}]} -------------------------------------------------------------------------------- /Module_5_Strings_and_Regular_Expressions/lab_10_strings.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"collapsed_sections":[],"authorship_tag":"ABX9TyMy3kJrZLBHsZC5P/rWyuVE"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Strings\n","\n","- creating a string\n","- string methods\n"],"metadata":{"id":"bHT9TEjSi0xk"}},{"cell_type":"code","source":["# Creating a String with single Quotes\n","String1 = 'Welcome to the Geeks World'\n","print(\"String with the use of Single Quotes: \")\n","print(String1)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"rL7qXxi3ky-k","executionInfo":{"status":"ok","timestamp":1666154989615,"user_tz":-330,"elapsed":10,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f6bdf940-7e57-43f1-a545-25046b96c84d"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["String with the use of Single Quotes: \n","Welcome to the Geeks World\n"]}]},{"cell_type":"code","source":["# Creating a String with double Quotes\n","String1 = \"I'm a Geek\"\n","print(\"\\nString with the use of Double Quotes: \")\n","print(String1)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"_s-xqVijk1dL","executionInfo":{"status":"ok","timestamp":1666154992638,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"4d7c30cd-3c9f-49ba-94dd-5c6217991312"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","String with the use of Double Quotes: \n","I'm a Geek\n"]}]},{"cell_type":"code","source":["# Creating a String with triple Quotes\n","String1 = '''I'm a Geek and I live in a world of \"Geeks\"'''\n","print(\"\\nString with the use of Triple Quotes: \")\n","print(String1)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"KWZxSHxDk6rM","executionInfo":{"status":"ok","timestamp":1666155054251,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"31066d4b-63d1-4aa7-eaef-262ed8aed8c3"},"execution_count":5,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","String with the use of Triple Quotes: \n","I'm a Geek and I live in a world of \"Geeks\"\n"]}]},{"cell_type":"code","source":["# Creating a String with triple double quote Quotes\n","String1 = \"\"\" I'm a Geek and I live in a world of \"Geeks\" \"\"\"\n","print(\"\\nString with the use of Triple Quotes: \")\n","print(String1)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"RwhLc_gplAbD","executionInfo":{"status":"ok","timestamp":1666155040698,"user_tz":-330,"elapsed":11,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"005f0468-8cdd-4e93-86c4-23f44e331287"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","String with the use of Triple Quotes: \n"," I'm a Geek and I live in a world of \"Geeks\" \n"]}]},{"cell_type":"markdown","source":["## acessing a string - indexing similar to list and tuple"],"metadata":{"id":"PadGKKYHlRar"}},{"cell_type":"code","execution_count":7,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"1TNmaY_3iQEA","executionInfo":{"status":"ok","timestamp":1666159219564,"user_tz":-330,"elapsed":403,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"ca5eeae3-0fc7-449a-9b1e-8bd25db8f6bd"},"outputs":[{"output_type":"stream","name":"stdout","text":["I\n"]}],"source":["st = 'I am learning Python in GDN 153'\n","print(st[0])"]},{"cell_type":"code","source":["# acess Python\n","print(st[14:20])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"TtdPhGpnlgji","executionInfo":{"status":"ok","timestamp":1666159237205,"user_tz":-330,"elapsed":433,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"9e8a25e7-bf02-44d5-e6ee-d110b0084938"},"execution_count":8,"outputs":[{"output_type":"stream","name":"stdout","text":["Python\n"]}]},{"cell_type":"code","source":["# access GDN 153\n","print(st[-7:])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"eaT8qcR0lld8","executionInfo":{"status":"ok","timestamp":1666159273411,"user_tz":-330,"elapsed":413,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"132a250f-1f99-4581-e9af-4eb9151db6b4"},"execution_count":9,"outputs":[{"output_type":"stream","name":"stdout","text":["GDN 153\n"]}]},{"cell_type":"code","source":["# negative index"],"metadata":{"id":"-YGd0DnuloUS"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["## replacing value\n","- replace GDN 153 to SJT 214 in above string"],"metadata":{"id":"KGE6csJflria"}},{"cell_type":"code","source":["st[-1]= \"4\"\n","print(st)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":186},"id":"SsBKwZLqmJ8r","executionInfo":{"status":"error","timestamp":1666159322476,"user_tz":-330,"elapsed":597,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"4083a7a7-b90b-4e1e-b6d4-29287f179c8c"},"execution_count":11,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mst\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m \u001b[0;34m\"4\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mst\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"]}]},{"cell_type":"code","source":[],"metadata":{"id":"WjIXg-nEmKaD"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["## string slicing, splitiing and stripping"],"metadata":{"id":"H7A63MgHmK0T"}},{"cell_type":"code","source":[],"metadata":{"id":"o86lcbKZlxBl"},"execution_count":null,"outputs":[]}]} -------------------------------------------------------------------------------- /Module_5_Strings_and_Regular_Expressions/lab_11_regular_expression.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyPDZ/h5NCgSczLQSuNOlym+"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Regular expression\n","- **Regular expressions** (RegEx)are a powerful language for matching text based on a pre-defined pattern.\n","- Example: finding mobile number, email id, finding URLS from HTML pages, extrating targeted content.\n","- The Python `re` module provides regular expression support.\n"," \n"," ```\n"," import re\n"," match = re.search(pat, str)\n"," ```\n","- The `re.search()` method takes a regular expression `pattern` and a `string` and searches for that pattern within the string.\n","- If the search is successful, search() returns a match `object` or `None` otherwise.\n","- It can detect the presence or absence of a text by matching it with a particular pattern.\n","- It can also split a pattern into one or more sub-patterns.\n"],"metadata":{"id":"Mh4Jqr49SAFy"}},{"cell_type":"code","source":["import re\n","match = re.search(r'C....', 'GeeksforGeeks: A computer science #CS110 \\\n"," portal for geeks C1234')\n","print(match)\n","print(match.group(0))\n"," \n","print('Start Index:', match.start())\n","print('End Index:', match.end())"],"metadata":{"id":"YhNG0numrl7a","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1672978956037,"user_tz":-330,"elapsed":3830,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"33bdaddb-781e-460b-a33f-bc6359d1437c"},"execution_count":6,"outputs":[{"output_type":"stream","name":"stdout","text":["\n","CS110\n","Start Index: 35\n","End Index: 40\n"]}]},{"cell_type":"code","source":["print(match.group(1))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":168},"id":"96NghlbzUCij","executionInfo":{"status":"error","timestamp":1672978958916,"user_tz":-330,"elapsed":9,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"e163f4c8-e45a-4d9d-9f14-ca780f1bcfd4"},"execution_count":7,"outputs":[{"output_type":"error","ename":"IndexError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmatch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgroup\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mIndexError\u001b[0m: no such group"]}]},{"cell_type":"code","source":["print(match.group(0))"],"metadata":{"id":"_5mpBahvUGNL"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["print(match.group(0))"],"metadata":{"id":"V0J-7k9ZUHU9"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# To search for the pattern 'word:' followed by a 3 letter word\n","import re\n","\n","str = 'an example word:cat!!'\n","match = re.search(r'word:\\w\\w\\w', str)\n","# If-statement after search() tests if it succeeded\n","if match:\n"," print('found', match.group()) ## 'found word:cat'\n","else:\n"," print('did not find')\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"PeqipGG_SqwB","executionInfo":{"status":"ok","timestamp":1672808967414,"user_tz":-330,"elapsed":453,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d3bc2a52-c15b-45cf-97cb-b6c9be97f6bd"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["found word:cat\n"]}]},{"cell_type":"markdown","source":["## Basic Patterns\n","- a, X, 9, < -- ordinary characters just match themselves exactly. \n","- The meta-characters which do not match themselves because they have special meanings are: . ^ $ * + ? { [ ] \\ | ( ) (details below).\n","\n","- . (a period) -- matches any single character except newline '\\n'\n","- \\w -- (lowercase w) matches a \"word\" character: a letter or digit or underbar [a-zA-Z0-9_]. **Note** : that although \"word\" is the mnemonic for this, it only matches a single word char, not a whole word.\n","- \\W (upper case W) matches any non-word character.\n","- \\b -- boundary between word and non-word\n","- \\s -- (lowercase s) matches a single whitespace character -- space, newline, return, tab, form [ \\n\\r\\t\\f]. \\S (upper case S) matches any non-whitespace character. \n","- \\t, \\n, \\r -- tab, newline, return\n","- \\d -- decimal digit [0-9] (some older regex utilities do not support \\d, but they all support \\w and \\s)\n","- ^ = start, $ = end -- match the start or end of the string\n","- \\ -- inhibit the \"specialness\" of a character. So, for example, use \\. to match a period or \\\\ to match a slash. If you are unsure if a character has special meaning, such as '@', you can try putting a slash in front of it, \\@. If its not a valid escape sequence, like \\c, your python program will halt with an error. "],"metadata":{"id":"8M97UmnOS4dr"}},{"cell_type":"code","source":[" ## Search for pattern 'iii' in string 'piiig'.\n"," ## All of the pattern must match, but it may appear anywhere.\n"," ## On success, match.group() is matched text.\n"," match = re.search(r'iii', 'piiig') # found, match.group() == \"iii\"\n"," print(match.group())\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"drC6Lis2T-va","executionInfo":{"status":"ok","timestamp":1672979372532,"user_tz":-330,"elapsed":651,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"6aae2b95-7066-48b1-e512-31a521a12f0d"},"execution_count":8,"outputs":[{"output_type":"stream","name":"stdout","text":["iii\n"]}]},{"cell_type":"code","source":[" match = re.search(r'igs', 'piiig') # not found, match == None\n"," print(match.group())\n"," \n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":204},"id":"P0W9NLibUNGi","executionInfo":{"status":"error","timestamp":1672979385163,"user_tz":-330,"elapsed":24,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"01bb368f-fe5e-4b3a-db13-abdf6ebbdc01"},"execution_count":9,"outputs":[{"output_type":"error","ename":"AttributeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmatch\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mre\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msearch\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mr'igs'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'piiig'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# not found, match == None\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmatch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgroup\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mAttributeError\u001b[0m: 'NoneType' object has no attribute 'group'"]}]},{"cell_type":"code","source":["## . = any char but \\n\n","match = re.search(r'..g', 'piiig') # found, match.group() == \"iig\"\n","print(match.group())\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"SH1QoBUNUZIs","executionInfo":{"status":"ok","timestamp":1672979429211,"user_tz":-330,"elapsed":660,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"5f382505-c4ce-48f7-fdd1-7d36c1395551"},"execution_count":10,"outputs":[{"output_type":"stream","name":"stdout","text":["iig\n"]}]},{"cell_type":"code","source":["## \\d = digit char, \\w = word char\n","match = re.search(r'\\d\\d\\d', 'p123g') # found, match.group() == \"123\"\n","print(match.group())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"UKKpzeh-Ud1y","executionInfo":{"status":"ok","timestamp":1672979498082,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"79a91021-bd10-4b79-8a71-b8aaab2e8a89"},"execution_count":14,"outputs":[{"output_type":"stream","name":"stdout","text":["123\n"]}]},{"cell_type":"code","source":["match = re.search(r'\\w\\w\\w\\w', '@@ab_cd!!') # found, match.group() == \"abc\"\n","print(match.group())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"JCMusX2OUV5M","executionInfo":{"status":"ok","timestamp":1672979543666,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d86eedf2-ccda-4c2a-b301-c227fd9e621d"},"execution_count":16,"outputs":[{"output_type":"stream","name":"stdout","text":["ab_c\n"]}]},{"cell_type":"markdown","source":["## Repetition\n","Things get more interesting when you use + and * to specify repetition in the pattern\n","\n"," - `+` -- 1 or more occurrences of the pattern to its left, e.g. 'i+' = one or more i's\n"," - `*` -- 0 or more occurrences of the pattern to its left\n"," - `?` -- match 0 or 1 occurrences of the pattern to its left \n","\n","### Leftmost & Largest\n","First the search finds the leftmost match for the pattern, and second it tries to use up as much of the string as possible -- i.e. `+` and `*` go as far as possible (the `+` and `*` are said to be `greedy`)."],"metadata":{"id":"h649oGJOUz9z"}},{"cell_type":"markdown","source":["### Repetition Examples"],"metadata":{"id":"1AeuR2bsVXj9"}},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"OrBnsERqR7Aq","executionInfo":{"status":"ok","timestamp":1666805273632,"user_tz":-330,"elapsed":513,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d5c40f43-de35-464e-d2d6-55e00327c1fe"},"outputs":[{"output_type":"stream","name":"stdout","text":["piii\n"]}],"source":["## i+ = one or more i's, as many as possible.\n","match = re.search(r'pi+', 'piiig') # found, match.group() == \"piii\"\n","print(match.group())\n"]},{"cell_type":"code","source":["## Finds the first/leftmost solution, and within it drives the +\n","## as far as possible (aka 'leftmost and largest').\n","## In this example, note that it does not get to the second set of i's.\n","match = re.search(r'i+', 'piigiiii') # found, match.group() == \"ii\"\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"g35gVXWoVjgh","executionInfo":{"status":"ok","timestamp":1666805296481,"user_tz":-330,"elapsed":616,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d9b27717-2b80-41ae-e0ea-580ac1c964c2"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["ii\n"]}]},{"cell_type":"code","source":["## \\s* = zero or more whitespace chars\n","## Here look for 3 digits, possibly separated by whitespace.\n","match = re.search(r'\\d\\s*\\d\\s*\\d', 'xx1 2 3xx') # found, match.group() == \"1 2 3\"\n","print(match.group())\n","match = re.search(r'\\d\\s*\\d\\s*\\d', 'xx12 3xx') # found, match.group() == \"12 3\"\n","print(match.group())\n","match = re.search(r'\\d\\s*\\d\\s*\\d', 'xx123xx') # found, match.group() == \"123\"\n","print(match.group())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"gGs1SgBOVpMc","executionInfo":{"status":"ok","timestamp":1666805326171,"user_tz":-330,"elapsed":485,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8443d709-9c53-4362-e7ea-82acd6eb0e50"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["1 2 3\n","12 3\n","123\n"]}]},{"cell_type":"code","source":["## ^ = matches the start of string, so this fails:\n","match = re.search(r'^b\\w+', 'ibargoo') # not found, match == None\n","print(match.group())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":204},"id":"XdIaGHRfVwaB","executionInfo":{"status":"error","timestamp":1672980771740,"user_tz":-330,"elapsed":1095,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"30b33b56-3cf1-44f4-9074-40199baf743a"},"execution_count":21,"outputs":[{"output_type":"error","ename":"AttributeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m## ^ = matches the start of string, so this fails:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mmatch\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mre\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msearch\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mr'^b\\w+'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'ibargoo'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# not found, match == None\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmatch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgroup\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mAttributeError\u001b[0m: 'NoneType' object has no attribute 'group'"]}]},{"cell_type":"code","source":["## but without the ^ it succeeds:\n","match = re.search(r'b\\w+', 'foobar') # found, match.group() == \"bar\"\n","print(match.group())\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"_Y0eDqisV4z6","executionInfo":{"status":"ok","timestamp":1672980779857,"user_tz":-330,"elapsed":14,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"3ab933e2-e0ac-4a83-a300-75bae03f4270"},"execution_count":22,"outputs":[{"output_type":"stream","name":"stdout","text":["bar\n"]}]},{"cell_type":"markdown","source":["### Email example"],"metadata":{"id":"ku6jPByxV98J"}},{"cell_type":"code","source":["str = 'purple alice-b@google.com monkey dishwasher'\n","match = re.search(r'\\w+@\\w+', str)\n","if match:\n"," print(match.group()) ## 'b@google'"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"fsFVueHMWACh","executionInfo":{"status":"ok","timestamp":1666805409681,"user_tz":-330,"elapsed":8,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"fb3b3caf-98ca-46e1-b31a-a14c1b7f9dca"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["b@google\n"]}]},{"cell_type":"code","source":["# - abc@vitstudent.ac.in, abc@vit.ac.in\n","str = 'purple alice-b@google.com monkey dishwasher abc@vit.ac.in dannfaoofew o'\n","match = re.search(r'([\\w.])+@vit(student)?.ac.in', str)\n","if match:\n"," print(match.group()) ## 'b@google'"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"LrqcJrXYbgRH","executionInfo":{"status":"ok","timestamp":1672981207887,"user_tz":-330,"elapsed":637,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"05e85d13-cea9-4a72-d7e5-034ec20fae1f"},"execution_count":30,"outputs":[{"output_type":"stream","name":"stdout","text":["abc@vit.ac.in\n"]}]},{"cell_type":"markdown","source":["#### Square brackets\n","- Square brackets can be used to indicate a set of chars, so [abc] matches 'a' or 'b' or 'c'.\n","- The codes \\w, \\s etc. work inside square brackets too with the one exception that dot (.) just means a literal dot.\n","- For the emails problem, the square brackets are an easy way to add '.' and '-' to the set of chars which can appear around the @ with the pattern r'[\\w.-]+@[\\w.-]+' to get the whole email address:"],"metadata":{"id":"eQzurQuTWGqJ"}},{"cell_type":"code","source":[" match = re.search(r'[\\w.-]+@[\\w.-]+', str)\n"," if match:\n"," print(match.group()) ## 'alice-b@google.com'"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"nf8tRP3LWJ8z","executionInfo":{"status":"ok","timestamp":1666805445412,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"811ecd02-fcf5-498d-90ac-003527df3b87"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["alice-b@google.com\n"]}]},{"cell_type":"markdown","source":["## Begining and start of the string"],"metadata":{"id":"E4qycjtvO6Ub"}},{"cell_type":"code","source":["# Beginning of String\n","import re\n","match = re.search(r'^Geek', 'Campus Geek of the month')\n","print('Beg. of String:', match)\n","\n","match = re.search(r'^Geek', 'Geek of the month')\n","print('Beg. of String:', match)\n","\n","# End of String\n","match = re.search(r'Geeks$', 'Compute science portal-GeeksforGeeks')\n","print('End of String:', match)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"swFa_aKFO80e","executionInfo":{"status":"ok","timestamp":1672809828289,"user_tz":-330,"elapsed":427,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"0487313d-5865-4dd9-91aa-4e762375e4dd"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Beg. of String: None\n","Beg. of String: \n","End of String: \n"]}]},{"cell_type":"code","source":["import re\n","print('Any Character=>', re.search(r'p.th.n', 'pUthon 3'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"JMthkJCbPaLG","executionInfo":{"status":"ok","timestamp":1672809953099,"user_tz":-330,"elapsed":3,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"28d47e7c-7f51-47f7-e391-af7f966b7002"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Any Character=> \n"]}]},{"cell_type":"code","source":["import re\n","print('Date{mm-dd-yyyy}:', re.search(r'(\\w+\\d+){1}-[\\d]{2}-[\\d]{4}','today date \\\n","is18is18-08-2020'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"fiSszfc1Pqa0","executionInfo":{"status":"ok","timestamp":1672810298948,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"0ed43f0f-8c46-4b2c-a4b1-939395be9ad7"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Date{mm-dd-yyyy}: \n"]}]},{"cell_type":"code","source":["import re\n","print('Date{mm-dd-yyyy}:', re.search(r'(\\w\\d+){4}','today date \\\n","is18is18-08-2020'))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"9rx0Wv8GRZNL","executionInfo":{"status":"ok","timestamp":1672810496893,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"80c5e8ce-5bc9-4e82-ff9d-013b440aeafa"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Date{mm-dd-yyyy}: \n"]}]},{"cell_type":"markdown","source":["## ## Regular expression common methods in python\n","- `re.find()`\n","- `re.findall()`\n","- `re.search()`\n","\n","**BeutufulSoup** : bs4 - a popular library based on re to rextract content from html, xml, etc."],"metadata":{"id":"4fgh8xdgPAnP"}}]} -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/Module_6_Files.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_6_Functions_and_Files/Module_6_Files.pptx -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/Module_6_Function.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_6_Functions_and_Files/Module_6_Function.pptx -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/file_read_1.py: -------------------------------------------------------------------------------- 1 | file_object = open('sample.txt', 'r') 2 | contents = file_object.read() 3 | print(contents) 4 | file_object.close() 5 | 6 | # import os 7 | 8 | # file_list = os.listdir() 9 | # print(file_list) -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/file_read_2.py: -------------------------------------------------------------------------------- 1 | file_object = open('sample.txt', 'r') 2 | line_list = file_object.readlines() 3 | print(line_list) 4 | # for line in line_list: 5 | # print(line) 6 | file_object.close() -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/file_read_write_demonstration.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "colab": { 8 | "base_uri": "https://localhost:8080/" 9 | }, 10 | "id": "v9Jw61NeVo28", 11 | "outputId": "3767d43b-bf59-47ab-93ab-73ae36b55dd3" 12 | }, 13 | "outputs": [ 14 | { 15 | "output_type": "stream", 16 | "name": "stdout", 17 | "text": [ 18 | "Mounted at /content/drive\n" 19 | ] 20 | } 21 | ], 22 | "source": [ 23 | "from google.colab import drive\n", 24 | "drive.mount('/content/drive', force_remount=True )" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": { 31 | "colab": { 32 | "base_uri": "https://localhost:8080/" 33 | }, 34 | "id": "cxgqKRZ0WI4S", 35 | "outputId": "69034ba5-ccd4-4024-b41f-60f3aa5b4f17" 36 | }, 37 | "outputs": [ 38 | { 39 | "output_type": "stream", 40 | "name": "stdout", 41 | "text": [ 42 | "/content/drive/MyDrive/VIT_Vellore/FALL_2022_2023/Python/Python_Lab/Computer_Programming_Python_BCSE101E\n" 43 | ] 44 | } 45 | ], 46 | "source": [ 47 | "import os\n", 48 | "base_path = '/content/drive/MyDrive/VIT_Vellore/FALL_2022_2023/Python/Python_Lab/Computer_Programming_Python_BCSE101E'\n", 49 | "\n", 50 | "%cd '/content/drive/MyDrive/VIT_Vellore/FALL_2022_2023/Python/Python_Lab/Computer_Programming_Python_BCSE101E'" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "colab": { 58 | "base_uri": "https://localhost:8080/" 59 | }, 60 | "id": "BjO14kLzWNvO", 61 | "outputId": "63240050-d2cd-4e08-c641-4cf5ae3d1d0c" 62 | }, 63 | "outputs": [ 64 | { 65 | "output_type": "stream", 66 | "name": "stdout", 67 | "text": [ 68 | "/content/drive/MyDrive/VIT_Vellore/FALL_2022_2023/Python/Python_Lab/Computer_Programming_Python_BCSE101E/Module_6_Functions_and_Files\n" 69 | ] 70 | } 71 | ], 72 | "source": [ 73 | "%cd Module_6_Functions_and_Files" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "source": [ 79 | "!ls" 80 | ], 81 | "metadata": { 82 | "colab": { 83 | "base_uri": "https://localhost:8080/" 84 | }, 85 | "id": "byTM8Jlln9yY", 86 | "outputId": "4f744282-bb20-4c1d-8ba8-648f5a344a25" 87 | }, 88 | "execution_count": null, 89 | "outputs": [ 90 | { 91 | "output_type": "stream", 92 | "name": "stdout", 93 | "text": [ 94 | " file_read_write_demonstration.ipynb Module_6_Files.gslides\n", 95 | "'Function Practice problems.gslides' Module_6_Function.pptx\n", 96 | " images\t\t\t\t sample.txt\n", 97 | " lab_11_2_function.ipynb\t VIT_BCSE101E_Functions.ipynb\n", 98 | " lab_11_functions_practice.ipynb\n" 99 | ] 100 | } 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": { 107 | "id": "XtNolVFUVo2-", 108 | "outputId": "01e71a3f-3d0d-474a-be72-30a76f72bbaf", 109 | "colab": { 110 | "base_uri": "https://localhost:8080/" 111 | } 112 | }, 113 | "outputs": [ 114 | { 115 | "output_type": "stream", 116 | "name": "stdout", 117 | "text": [ 118 | "S.No, RegistraionNo, Name\n", 119 | "2, 22BCE0076, Tashi Sharma\n", 120 | "40, 22BCE3064, Aryan Bhirud\n", 121 | "62, 22BCE3646, Diya Afreen Mukesh\n" 122 | ] 123 | } 124 | ], 125 | "source": [ 126 | "# To read contents of file\n", 127 | "file_object = open('sample.txt', 'r')\n", 128 | "contents = file_object.read()\n", 129 | "print(contents)\n", 130 | "file_object.close()" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "metadata": { 137 | "id": "F3NPMRQ9fUYu", 138 | "colab": { 139 | "base_uri": "https://localhost:8080/" 140 | }, 141 | "outputId": "423933b8-1a1a-4719-a2b9-3cd5b66763fb" 142 | }, 143 | "outputs": [ 144 | { 145 | "output_type": "stream", 146 | "name": "stdout", 147 | "text": [ 148 | "['S.No, RegistraionNo, Name', '2, 22BCE0076, Tashi Sharma', '40, 22BCE3064, Aryan Bhirud', '62, 22BCE3646, Diya Afreen Mukesh']\n", 149 | "--- S.No, RegistraionNo, Name\n", 150 | "--- 2, 22BCE0076, Tashi Sharma\n", 151 | "--- 40, 22BCE3064, Aryan Bhirud\n", 152 | "--- 62, 22BCE3646, Diya Afreen Mukesh\n" 153 | ] 154 | } 155 | ], 156 | "source": [ 157 | "line_list = contents.split('\\n')\n", 158 | "print(line_list)\n", 159 | "for item in line_list:\n", 160 | " print('---', item)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": { 167 | "id": "kuEzWgh8Vo3A", 168 | "outputId": "55dec840-0947-401c-b764-7fa0bf36824a", 169 | "colab": { 170 | "base_uri": "https://localhost:8080/" 171 | } 172 | }, 173 | "outputs": [ 174 | { 175 | "output_type": "stream", 176 | "name": "stdout", 177 | "text": [ 178 | "0 -> S.No, RegistraionNo, Name\n", 179 | "\n", 180 | "1 -> 2, 22BCE0076, Tashi Sharma\n", 181 | "\n", 182 | "2 -> 40, 22BCE3064, Aryan Bhirud\n", 183 | "\n", 184 | "3 -> 62, 22BCE3646, Diya Afreen Mukesh\n" 185 | ] 186 | } 187 | ], 188 | "source": [ 189 | "file_object = open('sample.txt', 'r')\n", 190 | "for i, line in enumerate(file_object):\n", 191 | " #if i%2 ==0:\n", 192 | " print(i,'->', line)\n", 193 | "file_object.close()" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": null, 199 | "metadata": { 200 | "id": "_uogDZ6YlyDT", 201 | "colab": { 202 | "base_uri": "https://localhost:8080/" 203 | }, 204 | "outputId": "2f9708c4-f770-4ab2-a1df-69e6630ec443" 205 | }, 206 | "outputs": [ 207 | { 208 | "output_type": "stream", 209 | "name": "stdout", 210 | "text": [ 211 | "S.No, RegistraionNo, Name\n", 212 | "2, 22BCE0076, Tashi Sharma\n", 213 | "40, 22BCE3064, Aryan Bhirud\n", 214 | "62, 22BCE3646, Diya Afreen Mukesh\n" 215 | ] 216 | } 217 | ], 218 | "source": [ 219 | " with open('sample.txt', 'r') as fin:\n", 220 | " content = fin.read()\n", 221 | " print (content)" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": { 228 | "id": "UdceENhUVo3D", 229 | "outputId": "a7c7db51-8607-4a10-bd9a-21fd701862ef", 230 | "colab": { 231 | "base_uri": "https://localhost:8080/" 232 | } 233 | }, 234 | "outputs": [ 235 | { 236 | "output_type": "stream", 237 | "name": "stdout", 238 | "text": [ 239 | "S.No, RegistraionNo, Name\n", 240 | "2, 22BCE0076, Tashi Sharma\n", 241 | "40, 22BCE3064, Aryan Bhirud\n", 242 | "62, 22BCE3646, Diya Afreen Mukesh\n" 243 | ] 244 | } 245 | ], 246 | "source": [ 247 | "file_object = open('sample.txt', 'r')\n", 248 | "for line in file_object:\n", 249 | " print(line.strip())\n", 250 | "file_object.close()" 251 | ] 252 | }, 253 | { 254 | "cell_type": "markdown", 255 | "metadata": { 256 | "id": "rnLtrkjLWd5p" 257 | }, 258 | "source": [ 259 | "### readlines and readlines()" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": null, 265 | "metadata": { 266 | "id": "TfdHGRfvVo3E", 267 | "outputId": "d76b856f-2103-4dcd-8a85-c1ff7c9e9010", 268 | "colab": { 269 | "base_uri": "https://localhost:8080/" 270 | } 271 | }, 272 | "outputs": [ 273 | { 274 | "output_type": "stream", 275 | "name": "stdout", 276 | "text": [ 277 | "['S.No, RegistraionNo, Name\\n', '2, 22BCE0076, Tashi Sharma\\n', '40, 22BCE3064, Aryan Bhirud\\n', '62, 22BCE3646, Diya Afreen Mukesh']\n", 278 | "S.No, RegistraionNo, Name\n", 279 | "\n", 280 | "2, 22BCE0076, Tashi Sharma\n", 281 | "\n", 282 | "40, 22BCE3064, Aryan Bhirud\n", 283 | "\n", 284 | "62, 22BCE3646, Diya Afreen Mukesh\n" 285 | ] 286 | } 287 | ], 288 | "source": [ 289 | "file_object = open('sample.txt', 'r')\n", 290 | "line_list = file_object.readlines()\n", 291 | "print(line_list)\n", 292 | "for line in line_list:\n", 293 | " print(line)\n", 294 | "file_object.close()" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "metadata": { 301 | "id": "vrptQjvliSDC" 302 | }, 303 | "outputs": [], 304 | "source": [ 305 | "print(line_list)" 306 | ] 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "metadata": { 311 | "id": "_n30AhUMWr3f" 312 | }, 313 | "source": [ 314 | "## Writing to files" 315 | ] 316 | }, 317 | { 318 | "cell_type": "code", 319 | "source": [ 320 | "!ls" 321 | ], 322 | "metadata": { 323 | "colab": { 324 | "base_uri": "https://localhost:8080/" 325 | }, 326 | "id": "g_4tS1LBqnSr", 327 | "outputId": "8e37ff40-623e-4224-ba6f-0b17e048c4db" 328 | }, 329 | "execution_count": null, 330 | "outputs": [ 331 | { 332 | "output_type": "stream", 333 | "name": "stdout", 334 | "text": [ 335 | " file_read_write_demonstration.ipynb Module_6_Files.gslides\n", 336 | "'Function Practice problems.gslides' Module_6_Function.pptx\n", 337 | " images\t\t\t\t sample.txt\n", 338 | " lab_11_2_function.ipynb\t VIT_BCSE101E_Functions.ipynb\n", 339 | " lab_11_functions_practice.ipynb\n" 340 | ] 341 | } 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": { 348 | "id": "OvfB3qBqVo3G" 349 | }, 350 | "outputs": [], 351 | "source": [ 352 | "fname = 'sample_out.csv'\n", 353 | "fo = open(fname, 'w')\n", 354 | "fo.write(\"I am, learning, Python\")\n", 355 | "fo.write(\" Python is, interesting, language\")\n", 356 | "fo.close()" 357 | ] 358 | }, 359 | { 360 | "cell_type": "code", 361 | "execution_count": null, 362 | "metadata": { 363 | "colab": { 364 | "base_uri": "https://localhost:8080/" 365 | }, 366 | "id": "eJ5JlvT7X83n", 367 | "outputId": "3c2d3e45-f09d-464b-e877-4ad585187c01" 368 | }, 369 | "outputs": [ 370 | { 371 | "output_type": "stream", 372 | "name": "stdout", 373 | "text": [ 374 | "total 1472\n", 375 | "-rw------- 1 root root 10406 Jan 10 12:33 file_read_write_demonstration.ipynb\n", 376 | "-rw------- 1 root root 178 Oct 19 12:51 'Function Practice problems.gslides'\n", 377 | "drwx------ 2 root root 4096 Dec 6 20:41 images\n", 378 | "-rw------- 1 root root 58131 Dec 20 11:58 lab_11_2_function.ipynb\n", 379 | "-rw------- 1 root root 9578 Dec 6 22:48 lab_11_functions_practice.ipynb\n", 380 | "-rw------- 1 root root 178 Jan 10 11:45 Module_6_Files.gslides\n", 381 | "-rw------- 1 root root 1255562 Dec 6 08:33 Module_6_Function.pptx\n", 382 | "-rw------- 1 root root 55 Jan 10 12:32 sample_out.csv\n", 383 | "-rw------- 1 root root 117 Jan 10 05:31 sample.txt\n", 384 | "-rw------- 1 root root 166030 Nov 29 15:43 VIT_BCSE101E_Functions.ipynb\n" 385 | ] 386 | } 387 | ], 388 | "source": [ 389 | "!ls -l" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "metadata": { 396 | "id": "nLZjQOo9YZ52", 397 | "colab": { 398 | "base_uri": "https://localhost:8080/" 399 | }, 400 | "outputId": "79dc8f16-c718-42a1-f780-d50acb47e4b5" 401 | }, 402 | "outputs": [ 403 | { 404 | "output_type": "stream", 405 | "name": "stdout", 406 | "text": [ 407 | "I am, learning, Python Python is, interesting, language" 408 | ] 409 | } 410 | ], 411 | "source": [ 412 | "!cat sample_out.csv" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "source": [ 418 | "fname = 'sample_out.csv'\n", 419 | "fo = open(fname, 'w')\n", 420 | "fo.write(\"Today is Tuesday\\n\")\n", 421 | "fo.write(\"We are learnign File concepts\")\n", 422 | "fo.close()" 423 | ], 424 | "metadata": { 425 | "id": "vCPeVZQWsOAD" 426 | }, 427 | "execution_count": null, 428 | "outputs": [] 429 | }, 430 | { 431 | "cell_type": "code", 432 | "source": [ 433 | "!cat sample_out.csv" 434 | ], 435 | "metadata": { 436 | "colab": { 437 | "base_uri": "https://localhost:8080/" 438 | }, 439 | "id": "2Fi8fWbBsJTI", 440 | "outputId": "482916bd-1e8f-4f53-f03a-26fa4fb88c4e" 441 | }, 442 | "execution_count": null, 443 | "outputs": [ 444 | { 445 | "output_type": "stream", 446 | "name": "stdout", 447 | "text": [ 448 | "Today is Tuesday\n", 449 | "We are learnign File concepts" 450 | ] 451 | } 452 | ] 453 | }, 454 | { 455 | "cell_type": "markdown", 456 | "metadata": { 457 | "id": "u7t4Q0tCXUXV" 458 | }, 459 | "source": [ 460 | "### Appending to files" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": null, 466 | "metadata": { 467 | "id": "YbXWoqi3XQoO" 468 | }, 469 | "outputs": [], 470 | "source": [ 471 | "fname = 'sample_out.csv'\n", 472 | "fo = open(fname, 'a')\n", 473 | "fo.write(\"\\nIN OOPS, we are going to, learn C and C plus\")\n", 474 | "fo.write(\"\\nC and C plus, will be, used in DSA\")\n", 475 | "fo.close()" 476 | ] 477 | }, 478 | { 479 | "cell_type": "code", 480 | "source": [ 481 | "!cat sample_out.csv" 482 | ], 483 | "metadata": { 484 | "colab": { 485 | "base_uri": "https://localhost:8080/" 486 | }, 487 | "id": "sMKULsZyt-XC", 488 | "outputId": "948711a0-18d7-4bf0-a602-b9a8743a003a" 489 | }, 490 | "execution_count": null, 491 | "outputs": [ 492 | { 493 | "output_type": "stream", 494 | "name": "stdout", 495 | "text": [ 496 | "Today is Tuesday\n", 497 | "We are learnign File concepts\n", 498 | "IN OOPS, we are going to, learn C and C plus\n", 499 | "C and C plus, will be, used in DSA" 500 | ] 501 | } 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": null, 507 | "metadata": { 508 | "colab": { 509 | "background_save": true, 510 | "base_uri": "https://localhost:8080/" 511 | }, 512 | "id": "QQ9ByN1TYQSO", 513 | "outputId": "af5d1e88-90fb-4703-b74f-243709f99f2b" 514 | }, 515 | "outputs": [ 516 | { 517 | "name": "stdout", 518 | "output_type": "stream", 519 | "text": [ 520 | "I am, learning, Python Python is, interesting, language\n", 521 | "\u001b[K\u001b[7m(END)\u001b[m\u001b[K" 522 | ] 523 | } 524 | ], 525 | "source": [ 526 | "!head sample_out.csv" 527 | ] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": null, 532 | "metadata": { 533 | "id": "EWgCqwAZXT0W", 534 | "colab": { 535 | "base_uri": "https://localhost:8080/" 536 | }, 537 | "outputId": "496b7f3a-5ad3-4bec-daf2-83385337700a" 538 | }, 539 | "outputs": [ 540 | { 541 | "output_type": "stream", 542 | "name": "stdout", 543 | "text": [ 544 | "['Today is Tuesday', 'We are learnign File concepts', 'IN OOPS, we are going to, learn C and C plus', 'C and C plus, will be, used in DSA']\n" 545 | ] 546 | } 547 | ], 548 | "source": [ 549 | "fname = 'sample_out.csv'\n", 550 | "fin = open(fname, 'r')\n", 551 | "st = fin.read()\n", 552 | "st_list = st.split('\\n')\n", 553 | "print(st_list)" 554 | ] 555 | }, 556 | { 557 | "cell_type": "code", 558 | "source": [ 559 | "\n", 560 | "st2_list = st.split(',')\n", 561 | "print(st2_list)" 562 | ], 563 | "metadata": { 564 | "colab": { 565 | "base_uri": "https://localhost:8080/" 566 | }, 567 | "id": "o_RbMuBTu2pB", 568 | "outputId": "977bda80-c237-4782-82db-5ef257c70e3d" 569 | }, 570 | "execution_count": null, 571 | "outputs": [ 572 | { 573 | "output_type": "stream", 574 | "name": "stdout", 575 | "text": [ 576 | "['Today is Tuesday\\nWe are learnign File concepts\\nIN OOPS', ' we are going to', ' learn C and C plus\\nC and C plus', ' will be', ' used in DSA']\n" 577 | ] 578 | } 579 | ] 580 | }, 581 | { 582 | "cell_type": "code", 583 | "source": [ 584 | "fin.close()" 585 | ], 586 | "metadata": { 587 | "id": "po1FGxNLvAiK" 588 | }, 589 | "execution_count": null, 590 | "outputs": [] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "source": [ 595 | "fin = open(fname, 'r')\n", 596 | "count =0\n", 597 | "while count!=4:\n", 598 | " print(fin.readline())\n", 599 | " count +=1" 600 | ], 601 | "metadata": { 602 | "colab": { 603 | "base_uri": "https://localhost:8080/" 604 | }, 605 | "id": "RW5UqIWPvCqr", 606 | "outputId": "aaadcb45-bfe3-4ba0-9d49-e03a03a57b29" 607 | }, 608 | "execution_count": null, 609 | "outputs": [ 610 | { 611 | "output_type": "stream", 612 | "name": "stdout", 613 | "text": [ 614 | "Today is Tuesday\n", 615 | "\n", 616 | "We are learnign File concepts\n", 617 | "\n", 618 | "IN OOPS, we are going to, learn C and C plus\n", 619 | "\n", 620 | "C and C plus, will be, used in DSA\n" 621 | ] 622 | } 623 | ] 624 | } 625 | ], 626 | "metadata": { 627 | "colab": { 628 | "provenance": [] 629 | }, 630 | "kernelspec": { 631 | "display_name": "Python 3.9.1 ('base')", 632 | "language": "python", 633 | "name": "python3" 634 | }, 635 | "language_info": { 636 | "codemirror_mode": { 637 | "name": "ipython", 638 | "version": 3 639 | }, 640 | "file_extension": ".py", 641 | "mimetype": "text/x-python", 642 | "name": "python", 643 | "nbconvert_exporter": "python", 644 | "pygments_lexer": "ipython3", 645 | "version": "3.9.1" 646 | }, 647 | "vscode": { 648 | "interpreter": { 649 | "hash": "a18277a3c17b13473a0914cd48d3a885ca187314fab77e224bb46140ca5f8a2a" 650 | } 651 | } 652 | }, 653 | "nbformat": 4, 654 | "nbformat_minor": 0 655 | } -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/images/factorial_function_recursive_call_stack.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_6_Functions_and_Files/images/factorial_function_recursive_call_stack.drawio.png -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/images/fibonacci_recursion_call_stack.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/durgeshbhagat/Computer_Programming_Python_BCSE101E/e6b1389765e51c15410b28519f1a658d4e94bba7/Module_6_Functions_and_Files/images/fibonacci_recursion_call_stack.drawio.png -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/lab_11_functions_practice.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyPDdAPv7jabQFjpDWv3E9MV"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Function \n","- A block of statements to perform a particular task.\n","## basic concept\n","- defining a function\n","- **def** and **return** *keyword*\n","- **function definition** vs **function call**\n","- parameters/arguements to function\n","\n","## Function examples\n","- to check whether a number is even or odd\n","- to check whther a number is prime or not\n","## Types of function"],"metadata":{"id":"Zvs5Ppj0kcXg"}},{"cell_type":"markdown","source":["#### To check whether a number is *Even* or *Odd*"],"metadata":{"id":"lgSL4Uj4lON2"}},{"cell_type":"markdown","source":["PART 1: Function Definition\n","- It tells us *How to do a particular task* ?"],"metadata":{"id":"fTqfOinPnk_Y"}},{"cell_type":"code","source":["# basic function - Function defintion\n","def check_even(num):\n"," if num%2==0:\n"," print('Even number')\n"," else:\n"," print('ODD number')"],"metadata":{"id":"-zCx_qjblEDR","executionInfo":{"status":"ok","timestamp":1670366633507,"user_tz":-330,"elapsed":475,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":1,"outputs":[]},{"cell_type":"markdown","source":["PART 2: Function Call\n","- It *call* or *performs* a particular task"],"metadata":{"id":"9xr2Ync9nnJo"}},{"cell_type":"code","source":["# Function call\n","check_even(5)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vvHGqbBBlHf-","executionInfo":{"status":"ok","timestamp":1670366634000,"user_tz":-330,"elapsed":40,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"fbd1f01f-0de4-4b3c-811f-9cc4e5d6d78f"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["ODD number\n"]}]},{"cell_type":"code","source":["check_even(8)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"hsz261r7lKZ3","executionInfo":{"status":"ok","timestamp":1670366634001,"user_tz":-330,"elapsed":37,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8ebc76ab-41f3-4b49-aa23-05cf4c554736"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["Even number\n"]}]},{"cell_type":"code","source":["# is this a function definition or function call\n","def Funpython():\n"," print('Python is fun ❤️')"],"metadata":{"id":"fGyFT57An0KP","executionInfo":{"status":"ok","timestamp":1670366634001,"user_tz":-330,"elapsed":34,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":4,"outputs":[]},{"cell_type":"code","source":["Funpython()"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Xqh0tL7On00t","executionInfo":{"status":"ok","timestamp":1670366634003,"user_tz":-330,"elapsed":36,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"919c6fe5-70e6-498d-a1e0-e7deac65fc16"},"execution_count":5,"outputs":[{"output_type":"stream","name":"stdout","text":["Python is fun ❤️\n"]}]},{"cell_type":"markdown","source":["#### To check whether a number is *prime* or not"],"metadata":{"id":"J9FyTSBslrMY"}},{"cell_type":"code","source":["def check_prime(n):\n"," is_prime = True\n"," for i in range(2,n):\n"," if n%i == 0: \n"," is_prime = False\n"," break\n"," return is_prime "],"metadata":{"id":"wtLCo9oElbkV","executionInfo":{"status":"ok","timestamp":1670366634004,"user_tz":-330,"elapsed":34,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":6,"outputs":[]},{"cell_type":"code","source":["print(check_prime(8))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"RZ_5UMU1lauW","executionInfo":{"status":"ok","timestamp":1670366634004,"user_tz":-330,"elapsed":33,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"57ac2e88-4e57-4fc5-d307-f52b7858af5f"},"execution_count":7,"outputs":[{"output_type":"stream","name":"stdout","text":["False\n"]}]},{"cell_type":"code","source":["print(check_prime(2))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"fOG9mFU5mGc-","executionInfo":{"status":"ok","timestamp":1670366634005,"user_tz":-330,"elapsed":31,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"aaa92885-cb1f-445a-e3f8-6dfb02530c02"},"execution_count":8,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n"]}]},{"cell_type":"code","source":["print(check_prime(11))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ZUF9jC6kmI8P","executionInfo":{"status":"ok","timestamp":1670366634006,"user_tz":-330,"elapsed":28,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"5903da8e-7828-4224-d9b3-cbc0b5d2de89"},"execution_count":9,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n"]}]},{"cell_type":"code","source":["print(check_prime(49))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"eV3enejLmOrV","executionInfo":{"status":"ok","timestamp":1670366634006,"user_tz":-330,"elapsed":25,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"a8174882-3bb8-408d-9a9a-666925e9a91a"},"execution_count":10,"outputs":[{"output_type":"stream","name":"stdout","text":["False\n"]}]},{"cell_type":"markdown","source":["### Built in funttion vs user defined fucntion\n","\n","### **Built in function** \n","- function defintion provided by python interpretor\n","- Examples\n"," - print( )\n"," - input( )\n"," - int( )\n"," - str( )\n"," - bool( )\n"," - enumerate( )\n"," - range( )\n"," - type( )\n"," - id( )\n"," - max( )\n","### **user-defined function** \n","- function defintion provided by python user"],"metadata":{"id":"ePI8g91AqSBT"}},{"cell_type":"markdown","source":["##### Examples of built-in functions"],"metadata":{"id":"7dgspel4rr3Z"}},{"cell_type":"code","source":["print('Learning python is Fun')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"2pu8w_NWqYVg","executionInfo":{"status":"ok","timestamp":1670366634007,"user_tz":-330,"elapsed":24,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"bee386b8-1e08-460b-dce5-b97540ff86bd"},"execution_count":11,"outputs":[{"output_type":"stream","name":"stdout","text":["Learning python is Fun\n"]}]},{"cell_type":"code","source":["print('Being pythonic is the way')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"THs6s1txrZio","executionInfo":{"status":"ok","timestamp":1670366634008,"user_tz":-330,"elapsed":21,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"93ddd985-20fe-46df-f279-3d6abb0e5e02"},"execution_count":12,"outputs":[{"output_type":"stream","name":"stdout","text":["Being pythonic is the way\n"]}]},{"cell_type":"code","source":["for num in range(0, 10):\n"," print(num)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"YLciqBlnrlZ0","executionInfo":{"status":"ok","timestamp":1670366634009,"user_tz":-330,"elapsed":19,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d149251f-defa-45a2-b4d1-433962c4e960"},"execution_count":13,"outputs":[{"output_type":"stream","name":"stdout","text":["0\n","1\n","2\n","3\n","4\n","5\n","6\n","7\n","8\n","9\n"]}]},{"cell_type":"code","source":["my_list = [\"Python\", \"C\", \"Cplus\", \"Java\", \"R\",\"Javascript\"]\n","print('List of popular languages')\n","for i, item in enumerate(my_list):\n"," print(f'- index:{i}, langugae name= {item}')"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"17s0nPkYr3P0","executionInfo":{"status":"ok","timestamp":1670366634010,"user_tz":-330,"elapsed":18,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8b43c522-62a7-44f6-b40f-68c385739c1f"},"execution_count":14,"outputs":[{"output_type":"stream","name":"stdout","text":["List of popular languages\n","- index:0, langugae name= Python\n","- index:1, langugae name= C\n","- index:2, langugae name= Cplus\n","- index:3, langugae name= Java\n","- index:4, langugae name= R\n","- index:5, langugae name= Javascript\n"]}]},{"cell_type":"markdown","source":["## More practice problems of Function\n"," 1. Write a function (WAF) to check whether a year is leap year or not.\n"," 2. WAF to find sum of all digits of a number.\n"," 3. WAF to find reverse the digits of a number.\n"," 4. WAF to find whether a number is perfect number or not.\n"," 5. WAF to find index and the value of maximum number from the list of integers.\n"," 6. WAF to find roots of a quadratic equation of the form: $ax^2 + bx +c$\n"," 7. WAF to find the aprox values of $e^x$ using taylor series approximation upto to n terms. $$F(x,n) = 1 + \\frac{x}{1!} + \\frac{x^2}{2!} + \\frac{x^3}{3!} + ... + \\frac{x^n}{n!}$$\n"," 8. WAF function to find aprox value of $e^x$ upto 3 decimal places using above taylore series forumale.\n"," 9. WAF to calculate the function: $$ f(X,W,b) = WX + b$$ where $W$ ia matrix of M*N dimension and $X$, $b$ is vector of $N$ dimension\n"," 10. WAF to print pascal traingle. Reference: https://leetcode.com/problems/pascals-triangle/\n"," |1|\n"," |1| |1|\n"," |1| |2| |1|\n"," |1| |3| |3| |1|\n"," |1| |4| |6| |4| | 1|\n","\n"],"metadata":{"id":"3iow0BaQsbkF"}}]} -------------------------------------------------------------------------------- /Module_6_Functions_and_Files/sample.txt: -------------------------------------------------------------------------------- 1 | <<<<<<< Updated upstream 2 | S.No, RegistraionNo, Name 3 | 2, 22BCE0076, Tashi Sharma 4 | 40, 22BCE3064, Aryan Bhirud 5 | ======= 6 | S.No, RegistraionNo, Name 7 | 2, 22BCE0076, Tashi Sharma 8 | 40, 22BCE3064, Aryan Bhirud 9 | >>>>>>> Stashed changes 10 | 62, 22BCE3646, Diya Afreen Mukesh -------------------------------------------------------------------------------- /Module_7_Modules_and_Packages/Pandas.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyOI+LwzWf2o0KGCjWiAPDaU"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":34,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":133},"id":"-h9LfajLiVOL","executionInfo":{"status":"error","timestamp":1674564692314,"user_tz":-330,"elapsed":395,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"3b45a607-1b48-42c5-ca52-a2e852fa4e14"},"outputs":[{"output_type":"error","ename":"SyntaxError","evalue":"ignored","traceback":["\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m - mainly used for data anylsis\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"]}],"source":["#Pandas\n","- mainly used for data anylsis\n","## Numpy vs Pandas\n","- Numpy supports only homegeneous data types\n","- whereas pandas also supports Heterogeneous data types\n","- Pandas can work with different fuile types like text, csv, excel etc"]},{"cell_type":"markdown","source":[],"metadata":{"id":"UFEqdMNTjOfR"}},{"cell_type":"code","source":["import pandas as pd\n","import numpy as np"],"metadata":{"id":"JaSE7rz1jQqQ","executionInfo":{"status":"ok","timestamp":1674564694443,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":35,"outputs":[]},{"cell_type":"code","source":["df = pd.DataFrame()"],"metadata":{"id":"Ab3mcA5gkbn5","executionInfo":{"status":"ok","timestamp":1674564694444,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":36,"outputs":[]},{"cell_type":"code","source":["print(df)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"D07zI5orkhTA","executionInfo":{"status":"ok","timestamp":1674564698762,"user_tz":-330,"elapsed":11,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b8d984cd-ed7e-489d-eb77-50cdca078d61"},"execution_count":37,"outputs":[{"output_type":"stream","name":"stdout","text":["Empty DataFrame\n","Columns: []\n","Index: []\n"]}]},{"cell_type":"code","source":["print(df.columns)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"sbZA-vMVku_-","executionInfo":{"status":"ok","timestamp":1674564698762,"user_tz":-330,"elapsed":9,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"9ecd443f-a8fe-4dfb-dbf7-2b09774eca84"},"execution_count":38,"outputs":[{"output_type":"stream","name":"stdout","text":["Index([], dtype='object')\n"]}]},{"cell_type":"markdown","source":["## Populating a Dataframe\n"," - Three ways \n"," - using list of list\n"," - using dictionary : column header as key with complete column as values \n"," - using list of dictionary \n"],"metadata":{"id":"mPLwnVsUi8EH"}},{"cell_type":"code","source":["# 1st approach using list of list\n","# student_list = [ ['80BCE3292', 'SHREYAS', 88], \\\n","# [ '82BCE1264', 'KURIAN', 66 ], \\\n","# [ 'Roll3', 'Name3', 87 ], \\\n","# [ 'Roll4', 'Name 4', 96], \\\n","\n","\n"," \n","# ]"],"metadata":{"id":"NCu3CagzStDP","executionInfo":{"status":"ok","timestamp":1674575069026,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":1,"outputs":[]},{"cell_type":"code","source":["st = \"\"\"22BCE3292\tSHREYAS SANTOSH KUMAR\tshreyas.santosh2022@vitstudent.ac.in \n","22BCE3478\tKURIAN AVARAN JOJO\tkurianavaran.jojo2022@vitstudent.ac.in\n","22BCE2612\tVARIN GURU\tvarin.guru2022@vitstudent.ac.in\n","22BCE2521\tAADHAVAN PONNIAH ANBUMUNEE\taadhavan.ponniah2022@vitstudent.ac.in\n","22BCE2652\tTANISHQ RAVISHANKAR TIWARI\ttanishq.ravishankar2022@vitstudent.ac.in\n","22BCE3184\tSAUMYA SAANVI\tsaumya.saanvi2022@vitstudent.ac.in\n","22BCE2893\tSAATVIK TIWARI\tsaatvik.tiwari2022@vitstudent.ac.in\n","22BCE2842\tRISHI KEDAR BONDRE\trishikedar.bondre2022@vitstudent.ac.in\n","22BCE2941\tATULYA JAYANT SAHANE\tatulyajayant.sahane2022@vitstudent.ac.in\n","22BCE3064\tARYAN BHIRUD\taryan.bhirud2022@vitstudent.ac.in\n","22BCE0166\tCHARAN ADITYA RAVICHANDRAN\tcharan.aditya2022@vitstudent.ac.in\n","22BCE3034\tM RISHI KRISHNAN\trishikrishnan.m2022@vitstudent.ac.in\"\"\""],"metadata":{"id":"O1Qmxtuxmw-I","executionInfo":{"status":"ok","timestamp":1674564702340,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":39,"outputs":[]},{"cell_type":"code","source":["student_list = []\n","line_list = st.split('\\n')\n","for i, line in enumerate(line_list):\n"," cur_line_list = line.strip().split()\n"," r_no = cur_line_list[0]\n"," name = ' '.join(cur_line_list[1:-1])\n"," email = cur_line_list[-1]\n"," student_list.append([ r_no, name, email])"],"metadata":{"id":"8qMzihRHnHb4","executionInfo":{"status":"ok","timestamp":1674564705010,"user_tz":-330,"elapsed":393,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":40,"outputs":[]},{"cell_type":"code","source":["for i, student in enumerate(student_list):\n"," print(i, student)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ht9VTreonbPP","executionInfo":{"status":"ok","timestamp":1674564705011,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"4d46b8a4-4ddb-477d-bded-aa0dd0fa10f7"},"execution_count":41,"outputs":[{"output_type":"stream","name":"stdout","text":["0 ['22BCE3292', 'SHREYAS SANTOSH KUMAR', 'shreyas.santosh2022@vitstudent.ac.in']\n","1 ['22BCE3478', 'KURIAN AVARAN JOJO', 'kurianavaran.jojo2022@vitstudent.ac.in']\n","2 ['22BCE2612', 'VARIN GURU', 'varin.guru2022@vitstudent.ac.in']\n","3 ['22BCE2521', 'AADHAVAN PONNIAH ANBUMUNEE', 'aadhavan.ponniah2022@vitstudent.ac.in']\n","4 ['22BCE2652', 'TANISHQ RAVISHANKAR TIWARI', 'tanishq.ravishankar2022@vitstudent.ac.in']\n","5 ['22BCE3184', 'SAUMYA SAANVI', 'saumya.saanvi2022@vitstudent.ac.in']\n","6 ['22BCE2893', 'SAATVIK TIWARI', 'saatvik.tiwari2022@vitstudent.ac.in']\n","7 ['22BCE2842', 'RISHI KEDAR BONDRE', 'rishikedar.bondre2022@vitstudent.ac.in']\n","8 ['22BCE2941', 'ATULYA JAYANT SAHANE', 'atulyajayant.sahane2022@vitstudent.ac.in']\n","9 ['22BCE3064', 'ARYAN BHIRUD', 'aryan.bhirud2022@vitstudent.ac.in']\n","10 ['22BCE0166', 'CHARAN ADITYA RAVICHANDRAN', 'charan.aditya2022@vitstudent.ac.in']\n","11 ['22BCE3034', 'M RISHI KRISHNAN', 'rishikrishnan.m2022@vitstudent.ac.in']\n"]}]},{"cell_type":"code","source":["df = pd.DataFrame(student_list, columns= ['RNo', 'Name', 'Email'])"],"metadata":{"id":"8jXDvYLroD62","executionInfo":{"status":"ok","timestamp":1674564709220,"user_tz":-330,"elapsed":6,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":42,"outputs":[]},{"cell_type":"code","source":["print(df.columns)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"9me3ZSA3oNVO","executionInfo":{"status":"ok","timestamp":1674564709221,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"8a821112-029a-40d9-8b54-b86966eb0c7c"},"execution_count":43,"outputs":[{"output_type":"stream","name":"stdout","text":["Index(['RNo', 'Name', 'Email'], dtype='object')\n"]}]},{"cell_type":"code","source":["print(df.head())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"xCB6YYFQoROS","executionInfo":{"status":"ok","timestamp":1674564710907,"user_tz":-330,"elapsed":5,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"aa25f5c6-7215-43f9-ca82-4dcada9caea2"},"execution_count":44,"outputs":[{"output_type":"stream","name":"stdout","text":[" RNo Name \\\n","0 22BCE3292 SHREYAS SANTOSH KUMAR \n","1 22BCE3478 KURIAN AVARAN JOJO \n","2 22BCE2612 VARIN GURU \n","3 22BCE2521 AADHAVAN PONNIAH ANBUMUNEE \n","4 22BCE2652 TANISHQ RAVISHANKAR TIWARI \n","\n"," Email \n","0 shreyas.santosh2022@vitstudent.ac.in \n","1 kurianavaran.jojo2022@vitstudent.ac.in \n","2 varin.guru2022@vitstudent.ac.in \n","3 aadhavan.ponniah2022@vitstudent.ac.in \n","4 tanishq.ravishankar2022@vitstudent.ac.in \n"]}]},{"cell_type":"code","source":["print(df['RNo'])"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"CIu93elkoxNg","executionInfo":{"status":"ok","timestamp":1674544636891,"user_tz":-330,"elapsed":9,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f5cea76f-1894-4419-cb49-2a2493766f34"},"execution_count":19,"outputs":[{"output_type":"stream","name":"stdout","text":["0 22BCE3292\n","1 22BCE3478\n","2 22BCE2612\n","3 22BCE2521\n","4 22BCE2652\n","5 22BCE3184\n","6 22BCE2893\n","7 22BCE2842\n","8 22BCE2941\n","9 22BCE3064\n","10 22BCE0166\n","11 22BCE3034\n","Name: RNo, dtype: object\n"]}]},{"cell_type":"code","source":["df['RNo'][2]"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":35},"id":"CQdRMmiKo8QW","executionInfo":{"status":"ok","timestamp":1674564714608,"user_tz":-330,"elapsed":413,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"49bf2670-1833-43a4-87d5-f62f6af2db99"},"execution_count":45,"outputs":[{"output_type":"execute_result","data":{"text/plain":["'22BCE2612'"],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":45}]},{"cell_type":"code","source":["print(df['RNo'].values.tolist())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"pevyZugxpLHH","executionInfo":{"status":"ok","timestamp":1674564717359,"user_tz":-330,"elapsed":9,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"4d404dac-4ea9-404a-8eb4-18e2c1d12000"},"execution_count":46,"outputs":[{"output_type":"stream","name":"stdout","text":["['22BCE3292', '22BCE3478', '22BCE2612', '22BCE2521', '22BCE2652', '22BCE3184', '22BCE2893', '22BCE2842', '22BCE2941', '22BCE3064', '22BCE0166', '22BCE3034']\n"]}]},{"cell_type":"code","source":["student_dictionary = {}\n","student_dictionary['RNo'] = df['RNo'].values.tolist()\n","student_dictionary['Name'] = df['Name'].values.tolist()\n","student_dictionary['Email'] = df['Email'].values.tolist()"],"metadata":{"id":"gToOD0-zpAUw","executionInfo":{"status":"ok","timestamp":1674564717361,"user_tz":-330,"elapsed":7,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":47,"outputs":[]},{"cell_type":"code","source":["df2 = pd.DataFrame(student_dictionary)\n","print(df2.head())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"dQ6_YEIjprlO","executionInfo":{"status":"ok","timestamp":1674564721440,"user_tz":-330,"elapsed":1040,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f64e3e03-f8c4-4ee5-bef8-ce608291f49b"},"execution_count":48,"outputs":[{"output_type":"stream","name":"stdout","text":[" RNo Name \\\n","0 22BCE3292 SHREYAS SANTOSH KUMAR \n","1 22BCE3478 KURIAN AVARAN JOJO \n","2 22BCE2612 VARIN GURU \n","3 22BCE2521 AADHAVAN PONNIAH ANBUMUNEE \n","4 22BCE2652 TANISHQ RAVISHANKAR TIWARI \n","\n"," Email \n","0 shreyas.santosh2022@vitstudent.ac.in \n","1 kurianavaran.jojo2022@vitstudent.ac.in \n","2 varin.guru2022@vitstudent.ac.in \n","3 aadhavan.ponniah2022@vitstudent.ac.in \n","4 tanishq.ravishankar2022@vitstudent.ac.in \n"]}]},{"cell_type":"code","source":["print(df)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"NwNAI1HQp2IX","executionInfo":{"status":"ok","timestamp":1674564721849,"user_tz":-330,"elapsed":4,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"9883e39f-67a2-4dde-cd3a-33fd33e4fa84"},"execution_count":49,"outputs":[{"output_type":"stream","name":"stdout","text":[" RNo Name \\\n","0 22BCE3292 SHREYAS SANTOSH KUMAR \n","1 22BCE3478 KURIAN AVARAN JOJO \n","2 22BCE2612 VARIN GURU \n","3 22BCE2521 AADHAVAN PONNIAH ANBUMUNEE \n","4 22BCE2652 TANISHQ RAVISHANKAR TIWARI \n","5 22BCE3184 SAUMYA SAANVI \n","6 22BCE2893 SAATVIK TIWARI \n","7 22BCE2842 RISHI KEDAR BONDRE \n","8 22BCE2941 ATULYA JAYANT SAHANE \n","9 22BCE3064 ARYAN BHIRUD \n","10 22BCE0166 CHARAN ADITYA RAVICHANDRAN \n","11 22BCE3034 M RISHI KRISHNAN \n","\n"," Email \n","0 shreyas.santosh2022@vitstudent.ac.in \n","1 kurianavaran.jojo2022@vitstudent.ac.in \n","2 varin.guru2022@vitstudent.ac.in \n","3 aadhavan.ponniah2022@vitstudent.ac.in \n","4 tanishq.ravishankar2022@vitstudent.ac.in \n","5 saumya.saanvi2022@vitstudent.ac.in \n","6 saatvik.tiwari2022@vitstudent.ac.in \n","7 rishikedar.bondre2022@vitstudent.ac.in \n","8 atulyajayant.sahane2022@vitstudent.ac.in \n","9 aryan.bhirud2022@vitstudent.ac.in \n","10 charan.aditya2022@vitstudent.ac.in \n","11 rishikrishnan.m2022@vitstudent.ac.in \n"]}]},{"cell_type":"code","source":["student_list_dictionary= []\n","for index, row in df.iterrows():\n"," r_no = row['RNo']\n"," name = row['Name']\n"," email = row['Email']\n"," temp_d = { 'RNo': r_no, 'Name' : name, 'Email' : email}\n"," student_list_dictionary.append(temp_d)\n"," print(index, r_no, name, email)\n","\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"_E8OuzDXrLiJ","executionInfo":{"status":"ok","timestamp":1674564725296,"user_tz":-330,"elapsed":406,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"fcd89380-89cc-465a-984a-72b2e69480b0"},"execution_count":50,"outputs":[{"output_type":"stream","name":"stdout","text":["0 22BCE3292 SHREYAS SANTOSH KUMAR shreyas.santosh2022@vitstudent.ac.in\n","1 22BCE3478 KURIAN AVARAN JOJO kurianavaran.jojo2022@vitstudent.ac.in\n","2 22BCE2612 VARIN GURU varin.guru2022@vitstudent.ac.in\n","3 22BCE2521 AADHAVAN PONNIAH ANBUMUNEE aadhavan.ponniah2022@vitstudent.ac.in\n","4 22BCE2652 TANISHQ RAVISHANKAR TIWARI tanishq.ravishankar2022@vitstudent.ac.in\n","5 22BCE3184 SAUMYA SAANVI saumya.saanvi2022@vitstudent.ac.in\n","6 22BCE2893 SAATVIK TIWARI saatvik.tiwari2022@vitstudent.ac.in\n","7 22BCE2842 RISHI KEDAR BONDRE rishikedar.bondre2022@vitstudent.ac.in\n","8 22BCE2941 ATULYA JAYANT SAHANE atulyajayant.sahane2022@vitstudent.ac.in\n","9 22BCE3064 ARYAN BHIRUD aryan.bhirud2022@vitstudent.ac.in\n","10 22BCE0166 CHARAN ADITYA RAVICHANDRAN charan.aditya2022@vitstudent.ac.in\n","11 22BCE3034 M RISHI KRISHNAN rishikrishnan.m2022@vitstudent.ac.in\n"]}]},{"cell_type":"code","source":["for i, stc in enumerate(student_list_dictionary):\n"," print(i, stc)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"1UN7logq1esE","executionInfo":{"status":"ok","timestamp":1674564776723,"user_tz":-330,"elapsed":403,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"f4227d48-3591-4bb0-8a98-7bfd8f1699fc"},"execution_count":51,"outputs":[{"output_type":"stream","name":"stdout","text":["0 {'RNo': '22BCE3292', 'Name': 'SHREYAS SANTOSH KUMAR', 'Email': 'shreyas.santosh2022@vitstudent.ac.in'}\n","1 {'RNo': '22BCE3478', 'Name': 'KURIAN AVARAN JOJO', 'Email': 'kurianavaran.jojo2022@vitstudent.ac.in'}\n","2 {'RNo': '22BCE2612', 'Name': 'VARIN GURU', 'Email': 'varin.guru2022@vitstudent.ac.in'}\n","3 {'RNo': '22BCE2521', 'Name': 'AADHAVAN PONNIAH ANBUMUNEE', 'Email': 'aadhavan.ponniah2022@vitstudent.ac.in'}\n","4 {'RNo': '22BCE2652', 'Name': 'TANISHQ RAVISHANKAR TIWARI', 'Email': 'tanishq.ravishankar2022@vitstudent.ac.in'}\n","5 {'RNo': '22BCE3184', 'Name': 'SAUMYA SAANVI', 'Email': 'saumya.saanvi2022@vitstudent.ac.in'}\n","6 {'RNo': '22BCE2893', 'Name': 'SAATVIK TIWARI', 'Email': 'saatvik.tiwari2022@vitstudent.ac.in'}\n","7 {'RNo': '22BCE2842', 'Name': 'RISHI KEDAR BONDRE', 'Email': 'rishikedar.bondre2022@vitstudent.ac.in'}\n","8 {'RNo': '22BCE2941', 'Name': 'ATULYA JAYANT SAHANE', 'Email': 'atulyajayant.sahane2022@vitstudent.ac.in'}\n","9 {'RNo': '22BCE3064', 'Name': 'ARYAN BHIRUD', 'Email': 'aryan.bhirud2022@vitstudent.ac.in'}\n","10 {'RNo': '22BCE0166', 'Name': 'CHARAN ADITYA RAVICHANDRAN', 'Email': 'charan.aditya2022@vitstudent.ac.in'}\n","11 {'RNo': '22BCE3034', 'Name': 'M RISHI KRISHNAN', 'Email': 'rishikrishnan.m2022@vitstudent.ac.in'}\n"]}]},{"cell_type":"code","source":["for index, row in df.iterrows():\n"," print(index, row, type(row))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"i5x157Y9r8BG","executionInfo":{"status":"ok","timestamp":1674545496429,"user_tz":-330,"elapsed":1350,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"b3486c08-3e50-47af-b766-4de408e40f13"},"execution_count":30,"outputs":[{"output_type":"stream","name":"stdout","text":["0 RNo 22BCE3292\n","Name SHREYAS SANTOSH KUMAR\n","Email shreyas.santosh2022@vitstudent.ac.in\n","Name: 0, dtype: object \n","1 RNo 22BCE3478\n","Name KURIAN AVARAN JOJO\n","Email kurianavaran.jojo2022@vitstudent.ac.in\n","Name: 1, dtype: object \n","2 RNo 22BCE2612\n","Name VARIN GURU\n","Email varin.guru2022@vitstudent.ac.in\n","Name: 2, dtype: object \n","3 RNo 22BCE2521\n","Name AADHAVAN PONNIAH ANBUMUNEE\n","Email aadhavan.ponniah2022@vitstudent.ac.in\n","Name: 3, dtype: object \n","4 RNo 22BCE2652\n","Name TANISHQ RAVISHANKAR TIWARI\n","Email tanishq.ravishankar2022@vitstudent.ac.in\n","Name: 4, dtype: object \n","5 RNo 22BCE3184\n","Name SAUMYA SAANVI\n","Email saumya.saanvi2022@vitstudent.ac.in\n","Name: 5, dtype: object \n","6 RNo 22BCE2893\n","Name SAATVIK TIWARI\n","Email saatvik.tiwari2022@vitstudent.ac.in\n","Name: 6, dtype: object \n","7 RNo 22BCE2842\n","Name RISHI KEDAR BONDRE\n","Email rishikedar.bondre2022@vitstudent.ac.in\n","Name: 7, dtype: object \n","8 RNo 22BCE2941\n","Name ATULYA JAYANT SAHANE\n","Email atulyajayant.sahane2022@vitstudent.ac.in\n","Name: 8, dtype: object \n","9 RNo 22BCE3064\n","Name ARYAN BHIRUD\n","Email aryan.bhirud2022@vitstudent.ac.in\n","Name: 9, dtype: object \n","10 RNo 22BCE0166\n","Name CHARAN ADITYA RAVICHANDRAN\n","Email charan.aditya2022@vitstudent.ac.in\n","Name: 10, dtype: object \n","11 RNo 22BCE3034\n","Name M RISHI KRISHNAN\n","Email rishikrishnan.m2022@vitstudent.ac.in\n","Name: 11, dtype: object \n"]}]},{"cell_type":"code","source":["df3 = pd.DataFrame(student_list_dictionary)"],"metadata":{"id":"ZcvBQvZMsc_W","executionInfo":{"status":"ok","timestamp":1674545609333,"user_tz":-330,"elapsed":403,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":32,"outputs":[]},{"cell_type":"code","source":["print(df3.head())"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"_OgzicC3sj--","executionInfo":{"status":"ok","timestamp":1674545617678,"user_tz":-330,"elapsed":17,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"1058ff91-27b5-48d4-8ce1-9d0b72fba37a"},"execution_count":33,"outputs":[{"output_type":"stream","name":"stdout","text":[" RNo Name \\\n","0 22BCE3292 SHREYAS SANTOSH KUMAR \n","1 22BCE3478 KURIAN AVARAN JOJO \n","2 22BCE2612 VARIN GURU \n","3 22BCE2521 AADHAVAN PONNIAH ANBUMUNEE \n","4 22BCE2652 TANISHQ RAVISHANKAR TIWARI \n","\n"," Email \n","0 shreyas.santosh2022@vitstudent.ac.in \n","1 kurianavaran.jojo2022@vitstudent.ac.in \n","2 varin.guru2022@vitstudent.ac.in \n","3 aadhavan.ponniah2022@vitstudent.ac.in \n","4 tanishq.ravishankar2022@vitstudent.ac.in \n"]}]}]} -------------------------------------------------------------------------------- /Module_7_Modules_and_Packages/numpy.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyMor/JchQm3A5lI/lH+Ced7"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":1,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ZF-puNQQud55","executionInfo":{"status":"ok","timestamp":1674574637199,"user_tz":-330,"elapsed":16,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"89b70a38-7b69-475b-c967-0460707f5527"},"outputs":[{"output_type":"stream","name":"stdout","text":["[2 3 4 5 6]\n","[3 4 5 6 7]\n","110\n"]}],"source":["import numpy as np\n","a = np.arange(2,7)\n","c = np.arange(3, 8)\n","print(a)\n","print(c)\n","print(np.dot(a,c))"]},{"cell_type":"code","source":["a = np.array([[1, 0],\n"," [0, 1]])\n","b = np.array([[4, 1],\n"," [2, 2]])"],"metadata":{"id":"yNkDjcf5ve3A","executionInfo":{"status":"ok","timestamp":1674574637200,"user_tz":-330,"elapsed":14,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}}},"execution_count":2,"outputs":[]},{"cell_type":"code","source":["print(np.matmul(a,b))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"m8fFgVacvfuh","executionInfo":{"status":"ok","timestamp":1674574637201,"user_tz":-330,"elapsed":15,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"d1386abd-045f-4182-d050-3fe1d0c72c91"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["[[4 1]\n"," [2 2]]\n"]}]},{"cell_type":"code","source":["a = np.array([[1, 0],\n"," [0, 1]])\n","b = np.array([[4, 1],\n"," [2, 2]])\n","print(np.matmul(a, b))\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Oo3jK-fTurgp","executionInfo":{"status":"ok","timestamp":1674574637202,"user_tz":-330,"elapsed":13,"user":{"displayName":"Durgesh Kumar","userId":"02847735510424621399"}},"outputId":"525b7c32-e30e-4e4a-cfaa-6ef2924eb7a3"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["[[4 1]\n"," [2 2]]\n"]}]}]} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Computer_Programming_Python_BCSE101E 2 | A course website for Computer Programming: Python BCSE101E 3 | ## Course Syllabus 4 | - Module_0: **Setting up the environment for python** 5 | - Installing Miniconda: creating an environment 6 | - Installing Visual Studio Code 7 | - Module_1: **Intrduction to Problem Solving** 8 | - Module_2: **Programming Fundamentals** 9 | - Introduction to python 10 | - Interactive and Script mode 11 | - Indentation, Comments 12 | - Variables, Reserved words 13 | - Data types, Operators and their precedence 14 | - Expresssion, Built-in function 15 | - Importing from Packages 16 | - Module_3: **Control Structure** 17 | - if, if-else, nested if, multiway elif 18 | - Looping: while, while-else, for loop, nested loop 19 | - break, continue, pass 20 | - Module_4: **Collections** 21 | - List: create, access, slicing, negative indices, list methods, list comprehensions 22 | - Tuples: create, indexing, slicing, operations on tuples 23 | - Dictionary: create, add, and replace values, operations on dictionaries 24 | - Sets: creation and operation 25 | - Module_5: **Strings and Regular Expressions** 26 | - String: comparision, formatting, slicing, splitting, stripping 27 | - Regular expressions: matching, search and replace, patterns 28 | - Module_6: **Functions and Files** 29 | - Functions: Parameters and Arguements: postional arguements, keyword arguements, paramaters with default values 30 | - Local and Global scope of variable 31 | - Functions with arbitrary arguements 32 | - Recursive functions - Lambda function 33 | - Files: create, open, read, write, append, close, tell and seek methods 34 | - Module_7: **Modules and Packages** 35 | - Built-in modules 36 | - User defined modules 37 | - Overview of Numpy and Pandas packages 38 | 39 | ## TextBooks 40 | 1. Eric Mathhes, Python Crash Course: A Hands-On, Project-Based Introdction to Programming, 2nd Edition, No starch Press, 2019 41 | --------------------------------------------------------------------------------