diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2558a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +convert_and_move_docs.py +.vscode/ +file_converter.py +Convert_and _move single.py +__pycache__/ +temp.html +markdown_converter.py +markdown_template.html +md_convert/ +Custom_nb_converter.py +nb_convert.py +temp.py +error.txt +files.txt +remove_rendered_md.bat diff --git a/.ipynb_checkpoints/Advanced_IO-checkpoint.ipynb b/.ipynb_checkpoints/Advanced_IO-checkpoint.ipynb index 5a0c673..0a753fc 100644 --- a/.ipynb_checkpoints/Advanced_IO-checkpoint.ipynb +++ b/.ipynb_checkpoints/Advanced_IO-checkpoint.ipynb @@ -103,6 +103,66 @@ "print(d, type(d), sep = '\\n')\n", "# Input: 10 20" ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10 20 30 40 50\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 \n", + "20 \n", + "[30, 40, 50] \n" + ] + } + ], + "source": [ + "# Var length input\n", + "a, b, *c = map(int, input().split())\n", + "print(a, type(a))\n", + "print(b, type(b))\n", + "print(c, type(c))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10 20 30\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 \n", + "20 \n", + "30 \n" + ] + } + ], + "source": [ + "# one line input\n", + "x, y, z = map(int, input().split())\n", + "print(x, type(x))\n", + "print(y, type(y))\n", + "print(z, type(z))" + ] } ], "metadata": { diff --git a/.ipynb_checkpoints/Cheat_sheet-checkpoint.pdf b/.ipynb_checkpoints/Cheat_sheet-checkpoint.pdf new file mode 100644 index 0000000..b429c88 Binary files /dev/null and b/.ipynb_checkpoints/Cheat_sheet-checkpoint.pdf differ diff --git a/.ipynb_checkpoints/Condition_Statements-checkpoint.ipynb b/.ipynb_checkpoints/Condition_Statements-checkpoint.ipynb index 76013ed..17194ac 100644 --- a/.ipynb_checkpoints/Condition_Statements-checkpoint.ipynb +++ b/.ipynb_checkpoints/Condition_Statements-checkpoint.ipynb @@ -4,7 +4,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Condition Statements\n", + "# Condition Statements\n", + "\n", "Condition statements or Control flow statements or Desicion Control Statements are statements that are used to control the flow or execution of a program.\n", "The flow is controlled the values of few variables that decide the proceedings of a program." ] @@ -40,8 +41,10 @@ "Executes the statements inside the block only if the condition is satisfied.\n", "\n", "Syntax: \n", - ">*if* condition: \n", - "     Statements" + "```python\n", + "if condition: \n", + " Statements\n", + "```" ] }, { @@ -74,20 +77,14 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 1, "metadata": {}, "outputs": [ - { - "name": "stdin", - "output_type": "stream", - "text": [ - " -1\n" - ] - }, { "name": "stdout", "output_type": "stream", "text": [ + "-1\n", "not zero\n" ] } @@ -108,10 +105,12 @@ "#### 2. *if - else* statements:\n", "Executes *else* when *if* condition fails \n", "Syntax: \n", - ">if condition1: \n", - "    Statements \n", + "```python\n", + "if condition1: \n", + " Statements \n", "else: \n", - "    Statements" + " Statements\n", + "```" ] }, { @@ -121,12 +120,14 @@ "#### 3. *if - elif - else* statements:\n", "Checks for truth of *elif* statement when *if* statement fails. Chain of *if-else* \n", "Syntax: \n", - ">if condition1: \n", - "    Statements\n", + "```python\n", + "if condition1: \n", + " Statements \n", "elif condition2: \n", - "    Statements\n", + " Statements \n", "else: \n", - "    Statements" + " Statements\n", + "```" ] }, { @@ -137,16 +138,18 @@ "*if else* within another *if else* statement\n", "\n", "Syntax:\n", - ">if condition1: \n", - "      if condition2: \n", - "         Statements \n", - "      else: \n", - "         Statements \n", + "```python\n", + "if condition1: \n", + " if condition2: \n", + " Statements \n", + " else: \n", + " Statements \n", "else: \n", - "      if condition3: \n", - "         Statements \n", - "      else: \n", - "         Statements " + " if condition3: \n", + " Statements \n", + " else: \n", + " Statements \n", + "```" ] }, { @@ -157,7 +160,9 @@ "One liner of *if else* statements\n", "\n", "Syntax:\n", - "> Statement1 if condition else Statement2" + "```python\n", + "Statement1 if condition else Statement2\n", + "```" ] } ], @@ -177,7 +182,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/DS_Dictionaries-checkpoint.ipynb b/.ipynb_checkpoints/DS_Dictionaries-checkpoint.ipynb new file mode 100644 index 0000000..566fa31 --- /dev/null +++ b/.ipynb_checkpoints/DS_Dictionaries-checkpoint.ipynb @@ -0,0 +1,1042 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Data Structures or Derived data Types in Python:\n", + "\n", + "Storing multiple values of same or different types under a single name.\n", + "They are collection of data.\n", + "\n", + "1. List\n", + "2. Tuple\n", + "3. String\n", + "4. Dictionary\n", + "5. Set \n", + "In this notebook, we'll discuss indepth on Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionary:\n", + "Dictionaries are unordered collection of data.\n", + "They are key-value mapping. \n", + "Represented by Curly braces `{}` \n", + "\n", + "```python\n", + "dictionary : {1: 10, 2: 20, 3: 30, 4: 'Hello', 5: -2.0}\n", + "```\n", + "\n", + "Defined by - key : value. \n", + "Each key-value map is separated by comma (,)\n", + "\n", + "|Keys| 1| 2| 3| 4| 5| \n", + "|---|---|---|---|---|---| \n", + "|Values| 10| 20| 30| 40| 50| " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a dictionary:\n", + "\n", + "1. '{ }'\n", + "2. dict()\n", + "\n", + "### 1. '{}'\n", + "```python\n", + "dict1 = {1:10, 2:20, 3:30}\n", + "```\n", + "### 2. dict()\n", + "Syntax: \n", + "```python\n", + "dict(iterable = None)\n", + "``` \n", + "iterable: any data structures listed above given that elements are present as key value mapping. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {}\n", + "type(d1)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{1: 10, 2: 20, 3: 35}\n" + ] + }, + { + "data": { + "text/plain": [ + "dict" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [(1, 10), (2, 20), (3, 35)]\n", + "d2 = dict(l)\n", + "print(d2)\n", + "type(d2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods or Functions in dictionaries: \n", + "There are various methods or functions that are used to work with dictionaries. \n", + "1. len \n", + "2. str \n", + "3. clear \n", + "4. copy \n", + "5. fromkeys \n", + "6. get \n", + "8. items \n", + "9. keys \n", + "10. values \n", + "11. update \n", + "12. pop\n", + "13. popitem\n", + "10. setdefault " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. len:\n", + "Returns the length of the given iterable.\n", + "\n", + "Syntax: \n", + "```python\n", + "len(iterable)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "len(d1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. str:\n", + "Returns the string format of the given dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "str(dict)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'{1: 12, 2: 23, 3: 34}'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "str(d1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. clear:\n", + "Deletes the items in the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.clear()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{}" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.clear()\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 4. copy:\n", + "Returns the shallow copy of the given dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.copy()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34}" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d2 = d1.copy()\n", + "d2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 5. fromkeys:\n", + "Returns a new dictionary form the given list of keys. By default the values are set to None.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.fromkeys(sep, val = None)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'key1': None, 'key2': None, 'key3': None}" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "key = ['key1', 'key2', 'key3']\n", + "d2 = dict.fromkeys(key)\n", + "d2" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'key1': 0, 'key2': 0, 'key3': 0}" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "key = ['key1', 'key2', 'key3']\n", + "d2 = dict.fromkeys(key, 0)\n", + "d2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6. get:\n", + "Returns the value of the given key if present else returns the default value given (None by Default).\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.get(key, default = None)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "12" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.get(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.get(4))" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.get(4, 0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 7. items:\n", + "Returns the list of key-value pairs in the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.items()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_items([(1, 12), (2, 23), (3, 34)])" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.items()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 8. keys:\n", + "Returns the list of keys present in the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.keys()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys([1, 2, 3])" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.keys()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 9. values:\n", + "Returns the list of values present on the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.values()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_values([12, 23, 34])" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.values()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 10. update:\n", + "Adds the key-value pairs in second dictionary to the first.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.update(dict)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34, 4: 45, 5: 56}" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d2 = {4: 45, 5: 56}\n", + "d1.update(d2)\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 11. pop:\n", + "Removes and returns the value of given key. If the key is absent, Error is raised if default is not given.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.pop(key, [default])\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "23\n" + ] + }, + { + "data": { + "text/plain": [ + "{1: 12, 3: 34}" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.pop(2))\n", + "d1" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "ename": "KeyError", + "evalue": "4", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0md1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m{\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m12\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m23\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m34\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0md1\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0md1\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mKeyError\u001b[0m: 4" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.pop(4))\n", + "d1" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "30\n" + ] + }, + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34}" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.pop(4, 30))\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 12. popitem:\n", + "Removes and returns the last key-value pair of the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.popitem()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(3, 34)\n" + ] + }, + { + "data": { + "text/plain": [ + "{1: 12, 2: 23}" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.popitem())\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 13. setdefault:\n", + "Sets the default value to key if the key is absent.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.setdefault(key, value)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34, 4: 45}" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.setdefault(4, 45)\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Accessing elements:\n", + "The values in the dictionary are accessed by key.\n", + "\n", + "Syntax: \n", + "```python\n", + "dictionary[key]\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "23" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1[2]" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "23" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 22: 23, 3: 34}\n", + "d1[22]" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "ename": "KeyError", + "evalue": "4", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0md1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m{\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m12\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m23\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m34\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0md1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mKeyError\u001b[0m: 4" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1[4]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Adding or Modifying items:\n", + "Items can be added or modified by using keys.\n", + "\n", + "If the key already exists, the value is replcaed by the new value. If not, new key-value pair is created\n", + "\n", + "Syntax: \n", + "```python\n", + "dictaionary[key] = value\n", + "``` " + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 24, 3: 34, 4: 45}" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1[2] = 24 # modify\n", + "d1[4] = 45 # add\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Delete Elements:\n", + "Elements can be deleted by using the *del* keyword.\n", + "\n", + "Syntax: \n", + "```python\n", + "del dict[key]\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12}" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "del d1[2], d1[3]\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing Items:\n", + "Use for loop to iterate through the dictionary." + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 12\n", + "2 23\n", + "3 34\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "for key, val in d1.items():\n", + " print(key, val)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sorting a dictionary:\n", + "Dictionaries are sorted only by keys." + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 12\n", + "2 23\n", + "3 34\n", + "\n", + "1 12\n", + "2 23\n", + "3 34\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "for i in sorted(d1.keys()):\n", + " print(i, d1[i])\n", + "print()\n", + "for i in sorted(d1):\n", + " print(i, d1[i])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested Dictionaries:\n", + "Dictionaries inside a dictionary is nested dictionary." + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 12\n", + "2 23\n", + "d {1: 12, 2: 23, 3: 34}\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 'd': {1: 12, 2: 23, 3: 34}}\n", + "for i,j in d1.items():\n", + " print(i,j)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries and list Comprehension:\n", + "Dictionaries can be defined by comprehensions.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict = {key: value (loops)}\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d2 = {x: x**2 for x in range(10)}\n", + "d2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries for switch case:\n", + "Dictionaries can be used as switch cases." + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'One'" + ] + }, + "execution_count": 55, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch = {1: 'One',\n", + " 2: 'Two', \n", + " 3: 'Three'}\n", + "switch[1]" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/.ipynb_checkpoints/DS_Lists-checkpoint.ipynb b/.ipynb_checkpoints/DS_Lists-checkpoint.ipynb index eb56ff1..39c8397 100644 --- a/.ipynb_checkpoints/DS_Lists-checkpoint.ipynb +++ b/.ipynb_checkpoints/DS_Lists-checkpoint.ipynb @@ -24,7 +24,9 @@ "## Lists:\n", "Lists are ordered collection of data.\n", "Represented by square brackets '[ ]' \n", - "`list : [10, 20, 30, 'Hello', -2.0]`\n", + "```python\n", + "list : [10, 20, 30, 'Hello', -2.0]\n", + "```\n", "\n", "Each value in the list is called a element \n", "order of elements: index of element \n", @@ -46,9 +48,14 @@ "2. list()\n", "\n", "### 1. '[ ]'\n", + "```python\n", "l = [10, 20, 30]\n", + "```\n", "### 2. list()\n", - "Syntax: `list(iterable = None)` \n", + "Syntax: \n", + "```python\n", + "list(iterable = None)\n", + "```\n", "iterable: any data structures listed above " ] }, @@ -120,8 +127,11 @@ "metadata": {}, "source": [ "### Getting list as input:\n", + "```python\n", "list1 = list(input()) \n", - "list1 = list(input().split())" + "list1 = list(input().split())\n", + "```\n", + "To know more on `split()`, find it in [Data Structures - Strings](DS_Strings.ipynb)" ] }, { @@ -218,23 +228,23 @@ "source": [ "## Methods or Functions in list:\n", "There are various methods or functions that are used to work on lists. \n", - "1. append\n", - "2. insert\n", - "3. pop\n", - "4. map\n", - "5. filter\n", - "6. sort\n", - "7. sorted\n", - "8. extend\n", - "9. index\n", - "10. remove\n", - "11. reduce\n", - "12. reverse\n", - "13. len\n", - "14. count\n", - "15. sum\n", - "16. max\n", - "17. min\n", + "1. append \n", + "2. insert \n", + "3. pop \n", + "4. map \n", + "5. filter \n", + "6. sort \n", + "7. sorted \n", + "8. extend \n", + "9. index \n", + "10. remove \n", + "11. reduce \n", + "12. reverse \n", + "13. len \n", + "14. count \n", + "15. sum \n", + "16. max \n", + "17. min \n", "18. enumerate" ] }, @@ -244,7 +254,10 @@ "source": [ "### 1. append:\n", "Adds the given element to the end of the list. \n", - "Syntax: `list.append(element)`" + "Syntax: \n", + "```python\n", + "list.append(element)\n", + "```" ] }, { @@ -277,12 +290,15 @@ "source": [ "### 2. insert:\n", "Inserts the element at the index specified \n", - "Syntax: `list.insert(index, element)`" + "Syntax: \n", + "```python\n", + "list.insert(index, element)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -291,7 +307,7 @@ "[10, 15, 20, 25, 35, 30]" ] }, - "execution_count": 15, + "execution_count": 1, "metadata": {}, "output_type": "execute_result" } @@ -312,7 +328,10 @@ "### 3. pop:\n", "Removes and returns the element from the index specified. Default is last element\n", "\n", - "Syntax: `list.pop(index = -1)`" + "Syntax: \n", + "```python\n", + "list.pop(index = -1)\n", + "```" ] }, { @@ -353,9 +372,12 @@ "metadata": {}, "source": [ "### 4. map:\n", - "Apllies the given function to every element in a list or iterable.\n", + "Applies the given function to every element in a list or iterable.\n", "\n", - "Syntax: `map(function, iterable)`" + "Syntax: \n", + "```python\n", + "map(function, iterable)\n", + "```" ] }, { @@ -435,7 +457,10 @@ "### 5. filter:\n", "Filters out the elements that match the given condition\n", "\n", - "Syntax: `filter(condition, iterable)`\n", + "Syntax: \n", + "```python\n", + "filter(condition, iterable)\n", + "```\n", "\n", "The condition should be given as a function definition which can be mapped to each variable. " ] @@ -466,7 +491,10 @@ "### 6. sort:\n", "Sorts the list as per the given condition\n", "\n", - "Syntax: `list.sort(key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "list.sort(key = None, reverse = False)\n", + "```" ] }, { @@ -507,7 +535,7 @@ ], "source": [ "l1 = ['Hi', 'Python', 'how', 'String', 'Data', 'Sorting Strings']\n", - "l1.sort()\n", + "l1.sort() #lexicographic sorting (as per unicode values)\n", "print(l1)\n", "l1.sort(key = len, reverse = True)\n", "print(l1)" @@ -520,28 +548,39 @@ "### 7. sorted:\n", "It is also function used to sort. Difference is that the sorted list should be reassigned to a variable.\n", "\n", - "Syntax: `sorted(iterable, key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "sorted(iterable, key = None, reverse = False)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 3, "metadata": {}, "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[10, 20, 50, 0, -10, -1, 100]\n" + ] + }, { "data": { "text/plain": [ "[-10, -1, 0, 10, 20, 50, 100]" ] }, - "execution_count": 17, + "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "l2 = [10, 20, 50, 0, -10, -1, 100]\n", - "l2 = sorted(l2)\n", + "l1 = [10, 20, 50, 0, -10, -1, 100]\n", + "l2 = sorted(l1)\n", + "print(l1)\n", "l2" ] }, @@ -552,7 +591,10 @@ "### 8. extend:\n", "Extends the given list using the elements of iterable, i.e. appends the elements of iterable to the given list \n", "\n", - "Syntax: `list.extend(iterable)`" + "Syntax: \n", + "```python\n", + "list.extend(iterable)\n", + "```" ] }, { @@ -606,7 +648,10 @@ "### 9. index:\n", "Returns the index of the element in the list. If multiple elements exist, it gives the index of first occurrence. If the element is not in the list, it raises an error\n", "\n", - "Syntax: `list.index(element)`" + "Syntax: \n", + "```python\n", + "list.index(element)\n", + "```" ] }, { @@ -637,7 +682,10 @@ "### 10. remove:\n", "Removes the first occurence of the element if present. Raises error when element not present\n", "\n", - "Syntax: `list.remove(value)`" + "Syntax: \n", + "```python\n", + "list.remove(value)\n", + "```" ] }, { @@ -690,7 +738,10 @@ "### 11. reduce:\n", "Sequentially applies the elements in the list to a function to give the final value. To use this we need to call *functools* module. In depth study of modules will be dealt later\n", "\n", - "Syntax: `reduce(function, list)`" + "Syntax: \n", + "```python\n", + "reduce(function, list)\n", + "```" ] }, { @@ -744,7 +795,10 @@ "### 12. reverse:\n", "Used to reverse the list.\n", "\n", - "Syntax: `list.reverse()`" + "Syntax: \n", + "```python\n", + "list.reverse()\n", + "```" ] }, { @@ -776,7 +830,10 @@ "### 13. len:\n", "Returns the length of the given iterable\n", "\n", - "Syntax: `len(iterable)`" + "Syntax: \n", + "```python\n", + "len(iterable)\n", + "```" ] }, { @@ -807,7 +864,10 @@ "### 14. count:\n", "Returns the count of the element specified\n", "\n", - "Syntax: `list.count(element)`" + "Syntax: \n", + "```python\n", + "list.count(element)\n", + "```" ] }, { @@ -846,7 +906,10 @@ "### 15. sum:\n", "returns the sum elements in the list or tuple.\n", "\n", - "Syntax: `sum(list, start = 0)`" + "Syntax: \n", + "```python\n", + "sum(list, start = 0)\n", + "```" ] }, { @@ -899,7 +962,10 @@ "### 16. max:\n", "Returns the maximum value in the list.\n", "\n", - "Syntax: `max(list, key = None)`" + "Syntax: \n", + "```python\n", + "max(list, key = None)\n", + "```" ] }, { @@ -951,7 +1017,10 @@ "### 17. min:\n", "Returns minimum value in the iterable\n", "\n", - "Syntax: `min(iterable, key = None)`" + "Syntax: \n", + "```python\n", + "min(iterable, key = None)\n", + "```" ] }, { @@ -982,7 +1051,10 @@ "### 18. enumerate:\n", "Returns the enumerate object for given list. An enumerate object is an iterable which contains ordered pair of the form `(index, value)` \n", "\n", - "Syntax: `enumerate(iterable, start = 0)`" + "Syntax: \n", + "```python\n", + "enumerate(iterable, start = 0)\n", + "```" ] }, { @@ -1024,8 +1096,8 @@ "|Negative Index| -5 | -4 | -3 | -2 | -1| \n", "\n", "Calling $i^{th}$ element: \n", - "positive index: l [i-1] \n", - "negative index: l [i - 1 - length]" + "positive index: `l[i-1]` \n", + "negative index: `l[i - 1 - length]`" ] }, { @@ -1079,9 +1151,12 @@ "metadata": {}, "source": [ "## Slicing operator:\n", - "Used to get / set a sublist of a list. Denoted by '[ ]'\n", + "Used to get / set a sublist of a list. Denoted by `'[]'`\n", "\n", - "Syntax: `list_name[start = 0 : stop = length : step = 1]`" + "Syntax: \n", + "```python\n", + "list_name[start = 0 : stop = length : step = 1]\n", + "```" ] }, { @@ -1234,8 +1309,11 @@ "It follows the form of the mathematical set-builder notation unlike the use of map and filter functions. It is used to create lists from either an existing like or a completely new list.\n", " \n", "Set bulider form:\n", - "{$x: x ~\\rm{\\epsilon~ list}$} \n", - "Example: `list1 = [expression (loops)]`" + "$\\{x: x ~\\rm{\\epsilon~ list}\\}$ \n", + "Example: \n", + "```python\n", + "list1 = [expression (loops)]\n", + "```" ] }, { @@ -1334,7 +1412,10 @@ "source": [ "## List Aliasing:\n", "Aliasing a list variable with another name. Referring a single list by multiple names. \n", - "Syntax: `new_name = old_name`" + "Syntax: \n", + "```python\n", + "new_name = old_name\n", + "```" ] }, { @@ -1384,7 +1465,10 @@ "### 1. Copy method:\n", "Creates a shallow copy of variable \n", "\n", - "Syntax: `new_list = list.copy(list_name)`" + "Syntax: \n", + "```python\n", + "new_list = list.copy(list_name)\n", + "```" ] }, { @@ -1416,7 +1500,10 @@ "### 2. slicing operator:\n", "Another method for shallow copy\n", "\n", - "Syntax: `new_list = old_list[:]`" + "Syntax: \n", + "```python\n", + "new_list = old_list[:]\n", + "```" ] }, { @@ -1448,7 +1535,10 @@ "### 3. list function:\n", "Create a new instance using list function. It also results in shallow copy\n", "\n", - "Syntax: `list_new = list(old_list)`" + "Syntax: \n", + "```python\n", + "list_new = list(old_list)\n", + "```" ] }, { @@ -1487,12 +1577,18 @@ "#### 1. copy:\n", "creates shallow copy\n", "\n", - "Syntax: `new_list = copy(list_name)`\n", + "Syntax: \n", + "```python\n", + "new_list = copy(list_name)\n", + "```\n", "\n", "#### 2. deepcopy:\n", "Creates a deep copy\n", "\n", - "Syntax: `new_list = deepcopy(list_name)`" + "Syntax: \n", + "```python\n", + "new_list = deepcopy(list_name)\n", + "```" ] }, { @@ -1535,10 +1631,16 @@ "## Multi-dimensional lists or matrices:\n", "Lists in a list is called a multidimensional list or nested lists. They are generally used to work with matrices.\n", "\n", - "Example: `list = [[10, 20, 30], [40, 50, 60]]` - Two dimensional list\n", + "Example: \n", + "```python\n", + "list = [[10, 20, 30], [40, 50, 60]] # - Two dimensional list\n", + "```\n", "\n", "### Accessing elements using index:\n", - "Syntax: `list_name[outermost list index][inner list index]...`" + "Syntax: \n", + "```python\n", + "list_name[outermost list index][inner list index]...\n", + "```" ] }, { @@ -1593,7 +1695,10 @@ "\n", "Each row of matrix is stored as a list\n", "\n", - "Example: `matrix = [[10, 20, 30], [40, 50, 60]]`\n", + "Example: \n", + "```python\n", + "matrix = [[10, 20, 30], [40, 50, 60]]\n", + "```\n", "\n", "### Matrix input:\n", "Matrix can be taken as input using loops or list comprehension." @@ -1756,7 +1861,7 @@ "A data type where elements are arranged such that the elements can only be added to and removed from the last. \n", "It follows the principle *FILO* - First In Last Out\n", "\n", - "**Methods used:** append() and pop()" + "**Methods used:** `append()` and `pop()`" ] }, { @@ -1767,7 +1872,7 @@ "A data type where elements are arranged such that the elements can only be added to the last and removed from the first. \n", "It follows the principle *FIFO* - First In First Out\n", "\n", - "**Methods Used:** append() and pop(0)" + "**Methods Used:** `append()` and `pop(0)`" ] }, { @@ -1780,11 +1885,11 @@ "### 1. Mutables:\n", "1. List\n", "2. Dictionary\n", + "4. Sets\n", "\n", "### 2. Immutable:\n", "1. Tuple\n", - "2. String\n", - "3. Sets" + "2. String" ] }, { @@ -1896,6 +2001,16 @@ "l4 = ['Namaste ', 'Hello']\n", "l4*5" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## List Comparison:\n", + "Python allows usage of relational operators on List.\n", + "\n", + "Python compares two lists using the elements present in them. Whenever a greater element is encounter thr boolean value is returned." + ] } ], "metadata": { @@ -1914,7 +2029,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/DS_Sets-checkpoint.ipynb b/.ipynb_checkpoints/DS_Sets-checkpoint.ipynb new file mode 100644 index 0000000..e8d8de6 --- /dev/null +++ b/.ipynb_checkpoints/DS_Sets-checkpoint.ipynb @@ -0,0 +1,977 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Data Structures or Derived data Types in Python:\n", + "\n", + "Storing multiple values of same or different types under a single name.\n", + "They are collection of data.\n", + "\n", + "1. List\n", + "2. Tuple\n", + "3. String\n", + "4. Dictionary\n", + "5. Set \n", + "In this notebook, we'll discuss indepth on Sets" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sets:\n", + "Sets are unordered collection of unique data.\n", + "Enclosed by Curly braces `{}` \n", + "\n", + "```python\n", + "set: {10, 20.2, 30.0}\n", + "```\n", + "\n", + "Each value in the set is called a element \n", + "Since set is unordered collection, it cannot be indexed. The elements are randomly stored." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a set:\n", + "\n", + "### set() method\n", + "\n", + "Syntax: \n", + "```python\n", + "set(iterable = None)\n", + "``` \n", + "iterable: any data structures listed above \n", + "\n", + "By default the `{}` map to a dictionary. So empty curly braces cannot be used." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30}" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [10, 20, 30]\n", + "s = set(l)\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30}" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s = {10, 20, 30, 10, 30}\n", + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Getting set as input:\n", + "```python\n", + "s1 = set(input()) \n", + "s2 = set(input().split())\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods or Functions in sets:\n", + "There are various methods or functions that are used to work on sets. \n", + "1. add \n", + "2. update \n", + "3. discard \n", + "4. pop \n", + "5. clear \n", + "6. len \n", + "7. issubset \n", + "8. issuperset \n", + "9. union \n", + "10. intersection \n", + "11. intersection_update \n", + "12. difference \n", + "13. symmetric_difference \n", + "14. copy \n", + "15. isdisjoint \n", + "16. max \n", + "17. min \n", + "18. enumerate\n", + "19. sum\n", + "20. sorted" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. add:\n", + "Adds an element to the end of the set.\n", + "\n", + "Syntax: `set.add(element)`" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30, 40}" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.add(40)\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. update:\n", + "Adds elements in another set to given set\n", + "\n", + "Syntax: `set.update(set)`" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 25, 30, 40}" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {10, 25, 40}\n", + "set1.update(set2)\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. discard:\n", + "Discards the given element in the set.\n", + "\n", + "Syntax: `set.discard(element)`" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 30}" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.discard(20)\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. pop:\n", + "Removes and returns a random element from set.\n", + "\n", + "Syntax: `set.pop()`" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.pop()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. clear:\n", + "Empties the set.\n", + "\n", + "Syntax: `set.clear()`" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "set()" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.clear()\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. len\n", + "Returns the length of the set\n", + "\n", + "Syntax: `len(set)`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. issubset:\n", + "Checks if a set subset of another.\n", + "\n", + "Syntax: `set.issubset(set)` \n", + "Or set1 <= set2" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {10, 20}\n", + "set2.issubset(set1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. issuperset:\n", + "Checks if the set superset of another.\n", + "\n", + "Syntax: `set.issuperset(set)` \n", + "Or set1 >= set2" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {10, 20, 30, 35}\n", + "set2.issuperset(set1) # set1.issubset(set2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9. union:\n", + "Returns the union of 2 sets\n", + "\n", + "Syntax: `set.union(set)` \n", + "Or set1|set2" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 12, 20, 22, 30}" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.union(set2)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 12, 20, 22, 30}" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1|set2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 10. intersection:\n", + "Returns the intersection of 2 sets\n", + "\n", + "Syntax: `set.intersection(set2)` \n", + "Or set1 & set2" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.intersection(set2)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1 & set2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 11. intersection_update:\n", + "Updates the set with intersection of given set.\n", + "\n", + "Syntax: `set.intersection_update(set)` \n", + "Or set1 &= set2" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.intersection_update(set2)\n", + "set1" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1 &= set2\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 12. difference:\n", + "Returns the set difference of given set\n", + "\n", + "Syntax: `set1-set2` \n", + "Or set1 - set2" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20}" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.difference(set2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 13. Symmetric Difference:\n", + "Returns the symmetric difference of two sets.\n", + "\n", + "Syntax: `set.symmetric_difference(set)`\n", + "Or set1 ^ set2" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 12, 20, 22}" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.symmetric_difference(set2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 14. copy:\n", + "Copies a set\n", + "\n", + "Syntax: `set.copy()`" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30}" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = set1.copy()\n", + "set2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 15. isdisjoint:\n", + "Checks if the given sets are mutually exclusive.\n", + "\n", + "Syntax: `set.isdisjoint(set)`" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {1, 22, -37}\n", + "set1.isdisjoint(set2)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "30" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [10, -10, 20, -30, 40]\n", + "sum(l)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 16. max:\n", + "Returns the maximum value in the set.\n", + "\n", + "Syntax: `max(set, key = None)`" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "50" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 15, 50, 21, -7}\n", + "max(l)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-7" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 15, 50, 21, -7, 7}\n", + "max(l, key = lambda x: x % 5) # Maximum reminder when divided by 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 17. min:\n", + "Returns minimum value in the iterable\n", + "\n", + "Syntax: `min(iterable, key = None)`" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-7" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 15, 50, 21, -7}\n", + "min(l)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 18. enumerate:\n", + "Returns the enumerate object for given set. An enumerate object is an iterable which contains ordered pair of the form `(index, value)` \n", + "\n", + "Syntax: `enumerate(iterable, start = 0)`" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(0, 10), (1, 'Hello'), (2, 20), (3, 'a'), (4, -1)]" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 20, 'Hello', 'a', -1}\n", + "list(enumerate(l))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 19. sum:\n", + "returns the sum elements in the set.\n", + "\n", + "Syntax: `sum(set, start = 0)`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 20. sorted:\n", + "It is a function used to sort.\n", + "\n", + "Syntax: `sorted(iterable, key = None, reverse = False)`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing the elements in a set:\n", + "1. Using loops\n", + "2. Using Variable length argument ( * )\n", + "\n", + "### 1. Looping:\n", + "Use for loop to access element.\n", + "\n", + "### 2. Using * :\n", + "Using * will convert the elements of into arguements of print method" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n", + "20\n", + "30\n" + ] + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "for i in set1:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 20 30\n" + ] + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "print(*set1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Comprehensions:" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = set(i+1 for i in range(0, 10))\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## all and any:\n", + "*any* checks if any of the element in an iterable is true.\n", + "\n", + "*all* checks if all the element on an iterable is True" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n" + ] + } + ], + "source": [ + "l = [10, 20, 30, 0]\n", + "print(any(l))\n", + "print(all(l))" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "True\n" + ] + } + ], + "source": [ + "set1 = {10, 20, 30, -1}\n", + "print(any(set1))\n", + "print(all(set1))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/.ipynb_checkpoints/DS_Strings-checkpoint.ipynb b/.ipynb_checkpoints/DS_Strings-checkpoint.ipynb index 773b4b2..12bd1b5 100644 --- a/.ipynb_checkpoints/DS_Strings-checkpoint.ipynb +++ b/.ipynb_checkpoints/DS_Strings-checkpoint.ipynb @@ -26,7 +26,9 @@ "Represented by quotes either ' ' or \" \". \n", "They are generally immutable. This means individual elements can't be changed.\n", "\n", - "`String : 'Hello', \"Python\"`\n", + "```python\n", + "Example: 'Hello', \"Python\"\n", + "```\n", "\n", "order of elements: index of element \n", "Index - may be positive or negative \n", @@ -47,9 +49,14 @@ "2. str()\n", "\n", "### 1. Quotes:\n", + "```python\n", "str = 'String'\n", + "```\n", "### 2. str()\n", - "Syntax: `str(value = None)` " + "Syntax: \n", + "```python\n", + "str(value = None)\n", + "``` " ] }, { @@ -155,7 +162,7 @@ "metadata": {}, "source": [ "### 1. Concatenation:\n", - "Two strings can be concatenated by using '+' operator." + "Two strings can be concatenated by using `+` operator." ] }, { @@ -185,7 +192,7 @@ "metadata": {}, "source": [ "### 2. Appending:\n", - "A character can be appended to string using '+=' operator or by reassignment." + "A character can be appended to string using `+=` operator or by reassignment." ] }, { @@ -216,7 +223,7 @@ "metadata": {}, "source": [ "### 3. String Multiplication:\n", - "String multiplication results a string with repitition. It can be done using ' * ' operator." + "String multiplication results a string with repitition. It can be done using `*` operator." ] }, { @@ -285,7 +292,10 @@ "### 1. capitalize:\n", "Capitalize the string. More specifically, first letter of the string in upper case and rest in lower case.\n", "\n", - "Syntax: `str.capitalize()`" + "Syntax: \n", + "```python\n", + "str.capitalize()\n", + "```" ] }, { @@ -317,7 +327,10 @@ "### 2. upper:\n", "Converts the string to upper case\n", "\n", - "Syntax: `str.upper()`" + "Syntax: \n", + "```python\n", + "str.upper()\n", + "```" ] }, { @@ -349,7 +362,10 @@ "### 3. lower:\n", "Converts the string to lowercase\n", "\n", - "Syntax: `str.lower()`" + "Syntax: \n", + "```python\n", + "str.lower()\n", + "```" ] }, { @@ -380,7 +396,10 @@ "### 4. center:\n", "Returns original string to center of given width. The empty places are filled using fillchar\n", "\n", - "Syntax: `str.center(width, fillchar)`" + "Syntax: \n", + "```python\n", + "str.center(width, fillchar)\n", + "```" ] }, { @@ -434,7 +453,10 @@ "### 5. swapcase:\n", "Swaps the case of string to lower if in uppercase, to upper in lowercase\n", "\n", - "Syntax: `str.swapcase()`" + "Syntax: \n", + "```python\n", + "str.swapcase()\n", + "```" ] }, { @@ -465,7 +487,10 @@ "### 6. find:\n", "Returns the index of start of substring if present in string else -1.\n", "\n", - "Syntax: `str.find(substring, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.find(substring, start = 0, end = length)\n", + "```" ] }, { @@ -496,7 +521,10 @@ "### 7. rfind:\n", "Returns index of start of last occurence substring if present in string else -1\n", "\n", - "Syntax: `str.rfind(substring, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.rfind(substring, start = 0, end = length)\n", + "```" ] }, { @@ -527,7 +555,10 @@ "### 8. index:\n", "Returns the index of substring given. Same as find but raises error if absent.\n", "\n", - "Syntax: `str.index(substring, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.index(substring, start = 0, end = length)\n", + "```" ] }, { @@ -558,7 +589,10 @@ "### 9. startswith:\n", "Checks if the given string starts with given Prefix.\n", "\n", - "Syntax: `str.startswith(prefix, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.startswith(prefix, start = 0, end = length)\n", + "```" ] }, { @@ -589,7 +623,10 @@ "### 10. endswith:\n", "Checks if the given string ends with the given suffix.\n", "\n", - "Syntax: `str.endswith(suffix, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.endswith(suffix, start = 0, end = length)\n", + "```" ] }, { @@ -620,7 +657,10 @@ "### 11. isalnum:\n", "Checks if the given string is alpha-numeric, i.e., contains only alphabets or numbers.\n", "\n", - "Syntax: `str.isalnum()`" + "Syntax: \n", + "```python\n", + "str.isalnum()\n", + "```" ] }, { @@ -672,7 +712,10 @@ "### 12. isalpha:\n", "Checks if the given string is alphabetic, i.e., contains only alphabets.\n", "\n", - "Syntax: `str.isalpha()`" + "Syntax: \n", + "```python\n", + "str.isalpha()\n", + "```" ] }, { @@ -724,7 +767,10 @@ "### 13. isdigit:\n", "Checks if the given string is numeric, i.e., contains only numbers.\n", "\n", - "Syntax: `str.isdigit()`" + "Syntax: \n", + "```python\n", + "str.isdigit()\n", + "```" ] }, { @@ -776,7 +822,10 @@ "### 14. strip:\n", "Removes the leading and trailing whitespaces by default, if any. If *chars* is given (string only), it removes only the characters in it.\n", "\n", - "Syntax: `str.strip(chars = None)`" + "Syntax: \n", + "```python\n", + "str.strip(chars = None)\n", + "```" ] }, { @@ -826,9 +875,12 @@ "metadata": {}, "source": [ "### 15. split:\n", - "Return a list of the words in the string, using *sep* as the delimiter. *maxsplit* gives the Maximum no. of splits to be done. The remaining string returned as last element. By default whitespaces, line feed and carriage returns are taken as delimiters.\n", + "Return a list of the words in the string, using `sep` as the delimiter. `maxsplit` gives the Maximum no. of splits to be done. The remaining string returned as last element. By default whitespaces, line feed and carriage returns are taken as delimiters.\n", "\n", - "Syntax: `str.split(/, sep = None, maxsplit = -1)`" + "Syntax: \n", + "```python\n", + "str.split(/, sep = None, maxsplit = -1)\n", + "```" ] }, { @@ -901,7 +953,10 @@ "### 16. join:\n", "Returns a concatenated string of iterable (containing only strings) with *char* (string) as delimiter.\n", "\n", - "Syntax: `char.join(iterable)`" + "Syntax: \n", + "```python\n", + "char.join(iterable)\n", + "```" ] }, { @@ -974,7 +1029,10 @@ "### 17. replace:\n", "Returns a copy of a string with given substring replaced by old substring. *count* is the max no. of occurences to be replaced, all be default.\n", "\n", - "Syntax: `str.replace(old_string, new_string, count = -1)`" + "Syntax: \n", + "```python\n", + "str.replace(old_string, new_string, count = -1)\n", + "```" ] }, { @@ -1005,7 +1063,10 @@ "### 18. zfill:\n", "Pads zeroes (0) to the start of the numeric string to fill the given width if width > length of string.\n", "\n", - "Syntax: `str.zfill(width)`" + "Syntax: \n", + "```python\n", + "str.zfill(width)\n", + "```" ] }, { @@ -1057,7 +1118,10 @@ "### 19. enumerate:\n", "Returns the enumeration object of given string.\n", "\n", - "Syntax: `enumerate(str)`" + "Syntax: \n", + "```python\n", + "enumerate(str)\n", + "```" ] }, { @@ -1091,7 +1155,10 @@ "### 20. len:\n", "Returns the length o given string\n", "\n", - "Syntax: `len(str)`" + "Syntax: \n", + "```python\n", + "len(str)\n", + "```" ] }, { @@ -1122,7 +1189,10 @@ "### 21. isupper:\n", "Checks if the given string is in uppercase.\n", "\n", - "Syntax: `str.isupper()`" + "Syntax: \n", + "```python\n", + "str.isupper()\n", + "```" ] }, { @@ -1153,7 +1223,10 @@ "### 22. islower:\n", "Checks if the given string is in lowercase.\n", "\n", - "Syntax: `str.islower()`" + "Syntax: \n", + "```python\n", + "str.islower()\n", + "```" ] }, { @@ -1184,7 +1257,10 @@ "### 23. lstrip:\n", "Removes the leading whitespaces by default, if any. If *chars* is given (string only), it removes only the characters in it.\n", "\n", - "Syntax: `str.lstrip(chars = None)`" + "Syntax: \n", + "```python\n", + "str.lstrip(chars = None)\n", + "```" ] }, { @@ -1215,7 +1291,10 @@ "### 24. rstrip:\n", "Removes the trailing whitespaces by default, if any. If *chars* is given (string only), it removes only the characters in it.\n", "\n", - "Syntax: `str.rstrip(chars = None)`" + "Syntax: \n", + "```python\n", + "str.rstrip(chars = None)\n", + "```" ] }, { @@ -1250,7 +1329,10 @@ "\n", "If the separator is not found, returns a 3-tuple containing the original string and two empty strings.\n", "\n", - "Syntax: `str.partition(sep)`" + "Syntax: \n", + "```python\n", + "str.partition(sep)\n", + "```" ] }, { @@ -1302,7 +1384,10 @@ "### 26. ljust:\n", "Pads given char (default - space) to the end of the string to fill the given width if width > length of string. Left justified string.\n", "\n", - "Syntax: `str.ljust(width, fillchar = ' ')`" + "Syntax: \n", + "```python\n", + "str.ljust(width, fillchar = ' ')\n", + "```" ] }, { @@ -1333,7 +1418,10 @@ "### 27. rjust:\n", "Pads given char (default - space) to the start of the string to fill the given width if width > length of string. Right justified string.\n", "\n", - "Syntax: `str.rjust(width, fillchar = ' ')`" + "Syntax: \n", + "```python\n", + "str.rjust(width, fillchar = ' ')\n", + "```" ] }, { @@ -1364,7 +1452,10 @@ "### 28. sorted:\n", "Returns sorted string as a list based on given key.\n", "\n", - "Syntax: `sorted(iterable, key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "sorted(iterable, key = None, reverse = False)\n", + "```" ] }, { @@ -1397,7 +1488,11 @@ "Elements of a string can be accessed using index.\n", "\n", "*Example:* \n", - "Consider a string, `s = 'Hello'`. Length = 5\n", + "Consider a string, \n", + "```python\n", + "s = 'Hello'\n", + "```\n", + "Length = 5\n", "\n", "| Element | 'H' | 'e' | 'l' | 'l' | 'o' | \n", "|---|---|---|---|---|---| \n", @@ -1435,9 +1530,12 @@ "metadata": {}, "source": [ "## Slicing operator:\n", - "Used to get a substring of a string. Denoted by '[ ]'\n", + "Used to get a substring of a string. Denoted by `[]`\n", "\n", - "Syntax: `string_name[start = 0 : stop = length : stride = 1]`" + "Syntax: \n", + "```python\n", + "string_name[start = 0 : stop = length : stride = 1]\n", + "```" ] }, { @@ -1470,10 +1568,10 @@ "2. Using * \n", "\n", "### 1. Looping:\n", - "Use for or while loop to access element or string.\n", + "Use *for* or *while* loop to access element or string.\n", "\n", "### 2. Using * :\n", - "Using * will convert the characters in the string into arguements of print method" + "Using `*` will convert the characters in the string into arguements of print method" ] }, { @@ -1542,12 +1640,18 @@ "### 1. ord:\n", "Returns the decimal ASCII (ordinal) value or Unicode point of given one-character string.\n", "\n", - "Syntax: `ord(c)`\n", + "Syntax: \n", + "```python\n", + "ord(c)\n", + "```\n", "\n", "### 2. chr:\n", "Returns the one character Unicode or ASCII string of given ordinal.\n", "\n", - "Syntax: `chr(i)`" + "Syntax: \n", + "```python\n", + "chr(i)\n", + "```" ] }, { @@ -1688,7 +1792,10 @@ "### 1. max:\n", "Returns the maximum value in the given string. Returns the character with maximum ASCII value in the String by default.\n", "\n", - "Syntax: `max(String, key = None)`" + "Syntax: \n", + "```python\n", + "max(String, key = None)\n", + "```" ] }, { @@ -1740,7 +1847,10 @@ "### 2. min:\n", "Returns minimum value in the string. Returns the character with minimum ASCII value in the String by default.\n", "\n", - "Syntax: `min(iterable, key = None)`" + "Syntax: \n", + "```python\n", + "min(iterable, key = None)\n", + "```" ] }, { @@ -1771,7 +1881,10 @@ "### 3. reversed:\n", "Returns iterator object of reversed string.\n", "\n", - "Syntax: `revrsed(sequence)`" + "Syntax: \n", + "```python\n", + "revrsed(sequence)\n", + "```" ] }, { @@ -1800,7 +1913,10 @@ "### 4. splitlines:\n", "Returns a list of strings split with carriage return and line feed (CRLF) as separator.\n", "\n", - "Syntax: `str.splitlines(keepends = False)`" + "Syntax: \n", + "```python\n", + "str.splitlines(keepends = False)\n", + "```" ] }, { @@ -1852,7 +1968,10 @@ "### 5. format:\n", "Returns formatted string as required.\n", "\n", - "Syntax: `str.format(*args, **kwargs)`\n", + "Syntax: \n", + "```python\n", + "str.format(*args, **kwargs)\n", + "```\n", "\n", "It was already discussed at String formatting in [Introduction to Python Programming](Introduction_to_Python_Programming.ipynb)" ] @@ -1882,7 +2001,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/DS_Tuples-checkpoint.ipynb b/.ipynb_checkpoints/DS_Tuples-checkpoint.ipynb index 301b559..fd57865 100644 --- a/.ipynb_checkpoints/DS_Tuples-checkpoint.ipynb +++ b/.ipynb_checkpoints/DS_Tuples-checkpoint.ipynb @@ -24,7 +24,9 @@ "## Tuple:\n", "Tuples are ordered collection of data. Unlike Lists they are immutable.\n", "Represented by parenthesis '( )' \n", - "`tuple : (10, 20, 30, 'Hello', -2.0)`\n", + "```python\n", + "tuple : (10, 20, 30, 'Hello', -2.0)\n", + "```\n", "\n", "Each value in the tuple is called a element \n", "order of elements: index of element \n", @@ -46,98 +48,80 @@ "2. tuple()\n", "\n", "### 1. '( )'\n", - "l = (10, 20, 30) \n", - "add a comma ',' if tuple is singleton\n", + "```python\n", + "l = (10, 20, 30)\n", + "``` \n", + "add a comma ',' if tuple is singleton,\n", + "\n", + "```python\n", + "t = (10,)\n", + "```\n", "### 2. tuple()\n", - "Syntax: `tuple(iterable = None)` \n", + "Syntax: \n", + "```python\n", + "tuple(iterable = None)\n", + "``` \n", "iterable: any data structures listed above " ] }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "(10, 30)\n" + "(10, 30)\n", + "\n" ] - }, - { - "data": { - "text/plain": [ - "tuple" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "t = (10, 30)\n", "print(t)\n", - "type(t)" + "print(type(t))" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "(10,)\n" + "(10,)\n", + "\n" ] - }, - { - "data": { - "text/plain": [ - "tuple" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "t1 = (10,)\n", "print(t1)\n", - "type(t1)" + "print(type(t1))" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "()\n" + "()\n", + "\n" ] - }, - { - "data": { - "text/plain": [ - "tuple" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "t2 = tuple()\n", "print(t2)\n", - "type(t2)" + "print(type(t2))" ] }, { @@ -156,29 +140,26 @@ "metadata": {}, "source": [ "### 1. Concatenation:\n", - "Two tuples can be concatenated by using '+' operator." + "Two tuples can be concatenated by using `+` operator." ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 4, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 30)" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] } ], "source": [ "t1 = (10, 20)\n", "t2 = (30,)\n", - "t1+t2" + "print(t1 + t2)" ] }, { @@ -186,30 +167,27 @@ "metadata": {}, "source": [ "### 2. Appending:\n", - "A tuples can be appended to string using '+=' operator or by reassignment." + "A tuples can be appended to string using `+=` operator or by reassignment." ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 5, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 30)" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] } ], "source": [ "t1 = (10, 20)\n", "t2 = (30,)\n", "t1 += t2\n", - "t1" + "print(t1)" ] }, { @@ -217,28 +195,25 @@ "metadata": {}, "source": [ "### 3. Tuple Multiplication:\n", - "Tuple multiplication results a new tuple with repitition. It can be done using ' * ' operator." + "Tuple multiplication results a new tuple with repitition. It can be done using `*` operator." ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 6, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 10, 20, 10, 20, 10, 20, 10, 20)" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 10, 20, 10, 20, 10, 20, 10, 20)\n" + ] } ], "source": [ "t1 = (10, 20)\n", - "t1*5" + "print(t1 * 5)" ] }, { @@ -270,31 +245,31 @@ "### 1. map:\n", "Applies the given function to every element in a iterable.\n", "\n", - "Syntax: `map(function, iterable)`" + "Syntax: \n", + "```python\n", + "map(function, iterable)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 10, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(3, 4, 5, 6)" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(3, 4, 5, 6)\n" + ] } ], "source": [ "def sample_fn(x):\n", - " return x+2\n", + " return x + 2\n", "t = [1, 2, 3, 4]\n", "t = tuple(map(sample_fn, t))\n", - "t" + "print(t)" ] }, { @@ -304,7 +279,10 @@ "### 2. filter:\n", "Filters out the elements that match the given condition\n", "\n", - "Syntax: `filter(condition, iterable)`\n", + "Syntax: \n", + "```python\n", + "filter(condition, iterable)\n", + "```\n", "\n", "The condition should be given as a function definition which can be mapped to each variable. " ] @@ -335,29 +313,29 @@ "### 3. sorted:\n", "Sorts the given tuple and returns a copy\n", "\n", - "Syntax: `sorted(iterable, key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "sorted(iterable, key = None, reverse = False)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 11, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(-10, -1, 0, 10, 20, 50, 100)" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(-10, -1, 0, 10, 20, 50, 100)\n" + ] } ], "source": [ "l2 = (10, 20, 50, 0, -10, -1, 100)\n", "l2 = tuple(sorted(l2))\n", - "l2" + "print(l2)" ] }, { @@ -367,28 +345,28 @@ "### 4. index:\n", "Returns the index of the element in the tuple. If multiple elements exist, it gives the index of first occurrence. If the element is not in the tuple, it raises an error\n", "\n", - "Syntax: `tuple.index(element)`" + "Syntax: \n", + "```python\n", + "tuple.index(element)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 12, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "0" - ] - }, - "execution_count": 20, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n" + ] } ], "source": [ "l = (10, 20, 30, 40, 10)\n", - "l.index(10)" + "print(l.index(10))" ] }, { @@ -398,23 +376,23 @@ "### 5. reduce:\n", "Sequentially applies the elements in the tuple to a function to give the final value. To use this we need to call *functools* module. In depth study of modules will be dealt later\n", "\n", - "Syntax: `reduce(function, tuple)`" + "Syntax: \n", + "```python\n", + "reduce(function, tuple)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 13, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "100" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "100\n" + ] } ], "source": [ @@ -425,7 +403,7 @@ "\n", "l = (10, 20, 30, 40)\n", "c = reduce(add, l)\n", - "c" + "print(c)" ] }, { @@ -452,7 +430,10 @@ "### 6. reversed:\n", "Returns iterator object of reversed tuple.\n", "\n", - "Syntax: `revrsed(sequence)`" + "Syntax: \n", + "```python\n", + "revrsed(sequence)\n", + "```" ] }, { @@ -481,28 +462,28 @@ "### 7. len:\n", "Returns the length of the given iterable\n", "\n", - "Syntax: `len(iterable)`" + "Syntax: \n", + "```python\n", + "len(iterable)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 14, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "6" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "6\n" + ] } ], "source": [ "list2 = (10, 20, 30, -1, 123, 10.0)\n", - "len(list2)" + "print(len(list2))" ] }, { @@ -512,36 +493,30 @@ "### 8. count:\n", "Returns the count of the element specified\n", "\n", - "Syntax: `tuple.count(element)`" + "Syntax: \n", + "```python\n", + "tuple.count(element)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "3\n" + "3\n", + "2\n" ] - }, - { - "data": { - "text/plain": [ - "2" - ] - }, - "execution_count": 25, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "l = (10, 20, 30, 10, 20, 25, 20, 50)\n", "print(l.count(20))\n", - "l.count(10)" + "print(l.count(10))" ] }, { @@ -551,28 +526,28 @@ "### 9. sum:\n", "Returns the sum elements in the tuple.\n", "\n", - "Syntax: `sum(tuple, start = 0)`" + "Syntax: \n", + "```python\n", + "sum(tuple, start = 0)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 16, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "30" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "30\n" + ] } ], "source": [ "l = (10, -10, 20, -30, 40)\n", - "sum(l)" + "print(sum(l))" ] }, { @@ -582,49 +557,46 @@ "### 10. max:\n", "Returns the maximum value in the tuple.\n", "\n", - "Syntax: `max(tuple, key = None)`" + "Syntax: \n", + "```python\n", + "max(tuple, key = None)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 17, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "50" - ] - }, - "execution_count": 27, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "50\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7)\n", - "max(l)" + "print(max(l))" ] }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 18, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "-7" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "-7\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7, 7)\n", - "max(l, key = lambda x: x % 5) # Maximum reminder when divided by 5" + "print(max(l, key=lambda x: x % 5)) # Maximum reminder when divided by 5" ] }, { @@ -634,49 +606,46 @@ "### 11. min:\n", "Returns minimum value in the iterable\n", "\n", - "Syntax: `min(iterable, key = None)`" + "Syntax: \n", + "```python\n", + "min(iterable, key = None)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 29, + "execution_count": 19, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "-7" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "-7\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7)\n", - "min(l)" + "print(min(l))" ] }, { "cell_type": "code", - "execution_count": 31, + "execution_count": 20, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "-7" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "-7\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7, 10.0)\n", - "min(l)" + "print(min(l))" ] }, { @@ -686,28 +655,28 @@ "### 12. enumerate:\n", "Returns the enumerate object for given tuple. An enumerate object is an iterable which contains ordered pair of the form `(index, value)` \n", "\n", - "Syntax: `enumerate(iterable, start = 0)`" + "Syntax: \n", + "```python\n", + "enumerate(iterable, start = 0)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 32, + "execution_count": 21, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "((0, 10), (1, 20), (2, 'Hello'), (3, 'a'), (4, -1))" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "((0, 10), (1, 20), (2, 'Hello'), (3, 'a'), (4, -1))\n" + ] } ], "source": [ "l = (10, 20, 'Hello', 'a', -1)\n", - "tuple(enumerate(l))" + "print(tuple(enumerate(l)))" ] }, { @@ -717,7 +686,10 @@ "### 13. zip:\n", "Returns zipped object containing order pairs of elements from given iterables.\n", "\n", - "Syntax: `zip(iterables)`" + "Syntax: \n", + "```python\n", + "zip(iterables)\n", + "```" ] }, { @@ -736,7 +708,7 @@ "source": [ "l = (10, 15, 50, 21, -7, 8)\n", "t = ['Ten', 'Fifteen', 'Fifty', 'Twenty One', 'Negative Seven']\n", - "print(*zip(l,t))" + "print(*zip(l, t))" ] }, { @@ -748,7 +720,11 @@ "Elements of a tuple can be accessed using index.\n", "\n", "*Example:* \n", - "Consider a tuple, `t = (10, 20, 30, 40, 50)`. Length = 5\n", + "Consider a tuple, \n", + "```python\n", + "t = (10, 20, 30, 40, 50)\n", + "```\n", + "Length = 5\n", "\n", "| Element | 10 | 20 | 30 | 40 | 50 | \n", "|---|---|---|---|---|---| \n", @@ -766,9 +742,12 @@ "metadata": {}, "source": [ "## Slicing operator:\n", - "Used to get / set a sub-tuple of a tuple. Denoted by '[ ]'\n", + "Used to get / set a sub-tuple of a tuple. Denoted by `[]`\n", "\n", - "Syntax: `tuple_name[start = 0 : stop = length : step = 1]`" + "Syntax: \n", + "```python\n", + "tuple_name[start = 0 : stop = length : step = 1]\n", + "```" ] }, { @@ -801,10 +780,10 @@ "2. Using * \n", "\n", "### 1. Looping:\n", - "Use for or while loop to access elements.\n", + "Use *for* or *while* loop to access elements.\n", "\n", "### 2. Using * :\n", - "Using * will convert the tuple elements into individual arguments of print method" + "Using `*` will convert the tuple elements into individual arguments of print method" ] }, { @@ -854,8 +833,11 @@ "It follows the form of the mathematical set-builder notation unlike the use of map and filter functions. It is used to create tuples from either an existing one or a completely new tuple.\n", " \n", "Set bulider form:\n", - "{$x: x ~\\rm{\\epsilon~ iterable}$} \n", - "Example: `l = tuple(expression (loops))`" + "$\\{x: x ~\\rm{\\epsilon~ iterable}\\}$ \n", + "Example: \n", + "```python\n", + "t = tuple(expression (loops))\n", + "```" ] }, { @@ -886,12 +868,19 @@ "metadata": {}, "source": [ "## Multi-dimensional tuples or matrices:\n", - "Like Lists, tuples in a tuple is called a multidimensional tuple or nested tuple. They are generally used to store matrices.\n", + "Like Lists, tuples / lists in a tuple is called a multidimensional tuple or nested tuple. They are generally used to store matrices.\n", "\n", - "Example: `list = ((10, 20, 30), (40, 50, 60))` - Two dimensional list\n", + "Example: \n", + "```python\n", + "t = ((10, 20, 30), (40, 50, 60))\n", + "# Two dimensional tuple\n", + "```\n", "\n", "### Accessing elements using index:\n", - "Syntax: `tuple_name[outermost tuple index][inner]...`" + "Syntax: \n", + "```python\n", + "tuple_name[outermost_tuple_index][inner]...[inner_most_index]\n", + "```" ] }, { @@ -903,7 +892,10 @@ "\n", "Each row of matrix is stored as a list / tuple\n", "\n", - "Example: `matrix = ([10, 20, 30], (40, 50, 60))`\n", + "Example: \n", + "```python\n", + "matrix = ([10, 20, 30], (40, 50, 60))\n", + "```\n", "\n", "### Matrix input:\n", "Matrix can be taken as input using loops or list comprehension." @@ -924,6 +916,16 @@ "## Variable length argument Tuples:\n", "The input given to variable length arguements are gathered together to form a tuple" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tuple Comparison:\n", + "Python allows usage of relational operators on Tuples.\n", + "\n", + "Python compares two tuples using the elements present in them. Whenever a greater element is encounter the boolean value is returned." + ] } ], "metadata": { @@ -942,7 +944,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/Errors_and_Exception_Handling-checkpoint.ipynb b/.ipynb_checkpoints/Errors_and_Exception_Handling-checkpoint.ipynb new file mode 100644 index 0000000..02ab436 --- /dev/null +++ b/.ipynb_checkpoints/Errors_and_Exception_Handling-checkpoint.ipynb @@ -0,0 +1,677 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "199a314e-264d-40a7-9acc-cf6e1843dba7", + "metadata": {}, + "source": [ + "# Errors and Exception" + ] + }, + { + "cell_type": "markdown", + "id": "e6044ca7-f38b-492b-b869-23f5409ac9e1", + "metadata": {}, + "source": [ + "## Error:\n", + "\n", + "Errors are the problems in a program due to which the program will stop the execution.\n", + "\n", + "[Some Common Errors](https://www.thecrazyprogrammer.com/2014/08/types-of-errors-in-programming.html)\n", + "\n", + "1. Syntax Errors\n", + "2. Run-time Errors\n", + "3. Logical Errors\n", + "4. Latent Errors" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "35bf50f2-6901-4407-a684-415f7ba3f569", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ArithmeticError\n", + "AssertionError\n", + "AttributeError\n", + "BlockingIOError\n", + "BrokenPipeError\n", + "BufferError\n", + "ChildProcessError\n", + "ConnectionAbortedError\n", + "ConnectionError\n", + "ConnectionRefusedError\n", + "ConnectionResetError\n", + "EOFError\n", + "EnvironmentError\n", + "FileExistsError\n", + "FileNotFoundError\n", + "FloatingPointError\n", + "IOError\n", + "ImportError\n", + "IndentationError\n", + "IndexError\n", + "InterruptedError\n", + "IsADirectoryError\n", + "KeyError\n", + "LookupError\n", + "MemoryError\n", + "ModuleNotFoundError\n", + "NameError\n", + "NotADirectoryError\n", + "NotImplementedError\n", + "OSError\n", + "OverflowError\n", + "PermissionError\n", + "ProcessLookupError\n", + "RecursionError\n", + "ReferenceError\n", + "RuntimeError\n", + "SyntaxError\n", + "SystemError\n", + "TabError\n", + "TimeoutError\n", + "TypeError\n", + "UnboundLocalError\n", + "UnicodeDecodeError\n", + "UnicodeEncodeError\n", + "UnicodeError\n", + "UnicodeTranslateError\n", + "ValueError\n", + "WindowsError\n", + "ZeroDivisionError\n", + "ArithmeticError\n", + "AssertionError\n", + "AttributeError\n", + "BlockingIOError\n", + "BrokenPipeError\n", + "BufferError\n", + "ChildProcessError\n", + "ConnectionAbortedError\n", + "ConnectionError\n", + "ConnectionRefusedError\n", + "ConnectionResetError\n", + "EOFError\n", + "EnvironmentError\n", + "FileExistsError\n", + "FileNotFoundError\n", + "FloatingPointError\n", + "IOError\n", + "ImportError\n", + "IndentationError\n", + "IndexError\n", + "InterruptedError\n", + "IsADirectoryError\n", + "KeyError\n", + "LookupError\n", + "MemoryError\n", + "ModuleNotFoundError\n", + "NameError\n", + "NotADirectoryError\n", + "NotImplementedError\n", + "OSError\n", + "OverflowError\n", + "PermissionError\n", + "ProcessLookupError\n", + "RecursionError\n", + "ReferenceError\n", + "RuntimeError\n", + "SyntaxError\n", + "SystemError\n", + "TabError\n", + "TimeoutError\n", + "TypeError\n", + "UnboundLocalError\n", + "UnicodeDecodeError\n", + "UnicodeEncodeError\n", + "UnicodeError\n", + "UnicodeTranslateError\n", + "ValueError\n", + "WindowsError\n", + "ZeroDivisionError\n" + ] + } + ], + "source": [ + "# list of Errors and exceptions\n", + "for i in dir(__builtins__) + dir(__builtin__):\n", + " if \"Error\" in i:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "id": "de9d7e7b-70f5-444f-88b5-a1f77d213d76", + "metadata": {}, + "source": [ + "## Exception:\n", + "\n", + "Exceptions are raised when the some internal events occur which changes the normal flow of the program." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "2b604b7f-9acf-4196-9ce3-45214b38adc8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "BaseException\n", + "Exception\n", + "BaseException\n", + "Exception\n" + ] + } + ], + "source": [ + "# list of Errors and exceptions\n", + "for i in dir(__builtins__) + dir(__builtin__):\n", + " if \"Exception\" in i:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "id": "4e8439e0-145b-46a5-9f3f-4624aa99b605", + "metadata": {}, + "source": [ + "## Traceback\n", + "The script used below is present [here](Errors_and_Exception.py)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "5e69d208-e867-431e-a8b1-58669ad3a798", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "In a\n", + "In b\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[1;36m42\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 10\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36ma\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"In a\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mb\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Back in a\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36mb\u001b[1;34m()\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"In b\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[1;36m42\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 10\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "def a():\n", + " print(\"In a\")\n", + " b()\n", + " print(\"Back in a\")\n", + "\n", + "def b():\n", + " print(\"In b\")\n", + " return 42/0\n", + "\n", + "a() " + ] + }, + { + "cell_type": "markdown", + "id": "8eb6ab0f-114b-49d8-8c74-e2739fb27edf", + "metadata": {}, + "source": [ + "## Exception Handling:\n", + "\n", + "Marking the error-prone zone and controlling what happens when an error / exception is raised is Exception Handling.\n", + "\n", + "In python, Exception Handling can be done using the following:\n", + "\n", + "1. *try* block\n", + "2. *except* block\n", + "3. *else* block\n", + "4. *finally* block\n", + "\n", + "Syntax:\n", + "```python\n", + "try:\n", + " # Statements - Critical or Error Prone statements\n", + "except ErrorOrExceptionType:\n", + " # Statements - What to do to handle errors\n", + "else:\n", + " # Statements - What to do when error is not encountered\n", + "finally:\n", + " # Statements - What to do at the end of Exception Handling\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "a8ee09fb-d589-4813-b9d2-79c0b12ee419", + "metadata": {}, + "source": [ + "### 1. *try* block:\n", + "\n", + "The critical operation that might not work as indented or may malfunction is enclosed in the `try` block. If the statement(s) raise any Error, the execution proceeding in the try block is terminated and moved to `except` block\n", + "```python\n", + "try:\n", + " # Statement(s) that may cause Errors\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "02ec15b9-b1cc-4b32-93d8-edaf77014593", + "metadata": {}, + "source": [ + "### 2. *except* block\n", + "\n", + "The `except` block accepts the error/exception call and works as intended. The except block is used to filter the error that is anticipated.\n", + "```python\n", + "except ErrorOrException:\n", + "```\n", + "The proper way of defining the except block is as above. \n", + "Though leaving out the Error name part works fine, it may cause a lot of confusion in many cases and is not recommended\n", + "```python\n", + "except: # Not recommended for use\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "814e2f34-6404-48a8-8125-7f4b1e6548a9", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 123\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = input()\n", + " print(n / 10)\n", + "except TypeError:\n", + " print(\"Error occurred\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "64e4accd-13a0-4eaa-bcc4-79f693529c18", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 159\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred\n" + ] + } + ], + "source": [ + "# Example - not recommended\n", + "try:\n", + " n = input()\n", + " print(n / 10)\n", + "except: # Don't do it this way\n", + " print(\"Error occurred\")" + ] + }, + { + "cell_type": "markdown", + "id": "71a9426e-ce09-4b2e-8189-88ab2b1b0267", + "metadata": {}, + "source": [ + "### 3. *else* block\n", + "\n", + "If there is no error in the code inside `try` block, the `except` block is skipped and the `else` block is executed.\n", + "\n", + "```python\n", + "else:\n", + " # Statement(s) to run when no error is caused\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "ed6c5684-0c6a-435e-b694-b05a10caa1fc", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.0\n", + "Safe\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = int(input())\n", + " print(10 / n)\n", + "except ZeroDivisionError: # Catch when there is division by zero (0)\n", + " print(\"Error occurred\")\n", + "else:\n", + " print(\"Safe\")" + ] + }, + { + "cell_type": "markdown", + "id": "fb3ba86d-87ff-4c4e-96a8-454f73384a28", + "metadata": {}, + "source": [ + "### 4. *finally* block\n", + "This block is executed at all cases, whether or not an error is encountered inside the `try` block\n", + "```python\n", + "finally:\n", + " # Statement(s)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "4d11fabc-2543-4492-9461-ee17fecdea37", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 0\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred\n", + "End of Program\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = int(input())\n", + " print(10 / n)\n", + "except ZeroDivisionError: # Catch when there is division by zero (0)\n", + " print(\"Error occurred\")\n", + "else:\n", + " print(\"Safe\")\n", + "finally:\n", + " print(\"End of Program\")" + ] + }, + { + "cell_type": "markdown", + "id": "fdef2ae9-2552-4a7f-b0b6-151210bb1edf", + "metadata": {}, + "source": [ + "#### *as* keyword in *except*\n", + "\n", + "Almost any case of exceptions returns a message about the cause of the error. The above defined method does not get the message for use, using `as` keyword, the error message can stored in a variable for use inside the except block.\n", + "```python\n", + "except ErrorOrException as err:\n", + " # Statement(s)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "e01e2dfd-1c55-401e-9190-446b95be8bc3", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 0\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred - division by zero\n", + "End of Program\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = int(input())\n", + " print(10 / n)\n", + "except ZeroDivisionError as e: # Catch when there is division by zero (0)\n", + " print(\"Error occurred -\", e) \n", + " # The message 'division by zero' is stored in e for use in the except block\n", + "else:\n", + " print(\"Safe\")\n", + "finally:\n", + " print(\"End of Program\")" + ] + }, + { + "cell_type": "markdown", + "id": "86e73074-5ef3-4e6c-989b-0da629ba7aa6", + "metadata": {}, + "source": [ + "## Intentionally Raising an Exception:\n", + "Python allows you to intentionally raise an exceptio at some cases using *raise* keyword.\n", + "\n", + "Syntax:\n", + "```python\n", + "raise ExceptionName(\"Message\")\n", + "```\n", + "\n", + "It is important to note that the exception following the `raise` keyword should either be an instance of a built-in exception or a class inheriting the same (Custom Exception)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "5cd07aff-ee0b-48ef-9e54-e9d2bc6bb928", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter temperature in Kelvin -1\n" + ] + }, + { + "ename": "ValueError", + "evalue": "The minimum temperature in Kelvin is absolute zero (0)", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mt\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Enter temperature in Kelvin\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mt\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"The minimum temperature in Kelvin is absolute zero (0)\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mt\u001b[0m \u001b[1;33m-\u001b[0m \u001b[1;36m273.15\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mValueError\u001b[0m: The minimum temperature in Kelvin is absolute zero (0)" + ] + } + ], + "source": [ + "# Example - Kelvin to Celsius Conversion\n", + "t = int(input(\"Enter temperature in Kelvin\"))\n", + "if t < 0:\n", + " raise ValueError(\"The minimum temperature in Kelvin is absolute zero (0)\")\n", + "else:\n", + " print(t - 273.15)" + ] + }, + { + "cell_type": "markdown", + "id": "7172133c-191e-4ae3-8fe0-7c9feb3c09e9", + "metadata": {}, + "source": [ + "## Assertion statement:\n", + "\n", + "An assertion is a sanity-check that you can turn on or turn off for testing your program.\n", + "\n", + "The easiest way to think of an assertion is to liken it to a `raise-if` statement (or to be more accurate, a raise-if-not statement). An expression or condition is tested, and if the result comes up false, an exception is raised.\n", + "\n", + "### *assert* Statement:\n", + "\n", + "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.\n", + "\n", + "```python\n", + "assert expression, \"Error message\"\n", + "```\n", + "The `assert` statement is usually enclosed by a `try` block and the exception is handled. In some cases to terminate the execution, they may not be used." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "dacfe853-1368-42ca-a88a-a0c71d25d8bc", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter temperature in Kelvin -1\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The minimum temperature in Kelvin is absolute zero (0)\n" + ] + } + ], + "source": [ + "# Example - Kelvin to Celsius Conversion\n", + "t = int(input(\"Enter temperature in Kelvin\"))\n", + "try:\n", + " assert t > 0, \"The minimum temperature in Kelvin is absolute zero (0)\"\n", + "except AssertionError as err:\n", + " print(err)\n", + "else:\n", + " print(t - 273.15)" + ] + }, + { + "cell_type": "markdown", + "id": "3181c04a-2ad4-414c-9f6d-355e3dcf9aa3", + "metadata": {}, + "source": [ + "## Creating custom Errors/Exception from built-ins:\n", + "Python has numerous built-in exceptions that force your program to output an error when something in the program goes wrong.\n", + "\n", + "However, sometimes you may need to create your own custom exceptions that serve your purpose.\n", + "\n", + "In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in `Exception` class. Most of the built-in exceptions are also derived from this class.\n", + "\n", + "```python\n", + "class My_exception(Exception):\n", + " pass\n", + "```\n", + "To know more about classes, visit [Object Oriented Programming](OOPS.ipynb)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "e31d9751-d85b-4a95-8832-f925e53e15a0", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 101\n" + ] + }, + { + "ename": "My_exception", + "evalue": "Number is large", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mMy_exception\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mn\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mn\u001b[0m \u001b[1;33m>\u001b[0m \u001b[1;36m100\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mMy_exception\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Number is large\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m \u001b[1;33m*\u001b[0m \u001b[0mn\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mMy_exception\u001b[0m: Number is large" + ] + } + ], + "source": [ + "class My_exception(Exception):\n", + " pass\n", + "\n", + "n = int(input())\n", + "if n > 100:\n", + " raise My_exception(\"Number is large\")\n", + "else:\n", + " print(2 * n)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.ipynb_checkpoints/Errors_and_exception-checkpoint.py b/.ipynb_checkpoints/Errors_and_exception-checkpoint.py new file mode 100644 index 0000000..8ec2517 --- /dev/null +++ b/.ipynb_checkpoints/Errors_and_exception-checkpoint.py @@ -0,0 +1,12 @@ +def a(): + print("In a") + b() + print("Back in a") + +def b(): + val = 52 + print("In b") + val + return val + +a() \ No newline at end of file diff --git a/.ipynb_checkpoints/Functions-checkpoint.ipynb b/.ipynb_checkpoints/Functions-checkpoint.ipynb index 66295e1..5cc6c20 100644 --- a/.ipynb_checkpoints/Functions-checkpoint.ipynb +++ b/.ipynb_checkpoints/Functions-checkpoint.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Functions in Python:\n", + "# Functions in Python\n", "Function is a set of organized lines of code that performs a specific, well defined task.\n", "\n", "It is used reduce the number of lines of code and improve reusability." @@ -15,20 +15,25 @@ "metadata": {}, "source": [ "Syntax: \n", - "*def* function_name(parameters): => function definition \n", - "     Statements \n", - "      *return* value(s)\n", + "```python\n", + "def function_name(parameters): # function definition \n", + " Statements\n", + " return value(s)\n", "\n", "... \n", "... \n", - "function_name(parameters) => Caller" + "function_name(parameters) # Caller\n", + "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Return statement:(*return*)\n", + "#### Return statement:\n", + "```python\n", + "return\n", + "```\n", "Returns back a value as specified. It marks the end of a function\n" ] }, @@ -42,7 +47,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -64,7 +69,7 @@ "source": [ "# Example 1:\n", "def add(a, b): # Function Definition\n", - " return a+b # returns the sum\n", + " return a + b # returns the sum\n", "x = int(input())\n", "y = int(input())\n", "print(add(x, y)) # Function Calling\n", @@ -73,20 +78,39 @@ "# 13" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Naming a function\n", + "\n", + "Like variables, python functions should also be in `lower_snake_case`\n", + "\n", + "One of the more universal, yet simple rules is: Function names should be verbs if the function changes the state of the program, and nouns if they're used to return a certain value.\n", + "\n", + "1. *Self-explanatory names*: a function `get_name()` will tell the developer what it returns as well as set_address(), is_male(), etc.\n", + "2. *Short*: a function name must be as short as possible so that it's simple to type as well as easy to remember. A function `get_number_of_pages_in_the_book()` is not good, something like `get_book_page_count()` is better.\n", + "3. Use of prefixes: use prefixes in the functions such as `get_name()`, `set_name()`, etc.\n", + "\n", + "The most important thing to note is to follow a constant naming convention throughout the function" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lambda function (Inline or Anonymous function):\n", - "One liner of a function\n", + "One liner of a function. It is created for use at one point or one statememt and is not intended to be named and stored.\n", "\n", "Syntax: \n", - "*lambda* parameters: Statement\n" + "```python\n", + "lambda parameters: Statement\n", + "```" ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -100,21 +124,33 @@ "name": "stdout", "output_type": "stream", "text": [ - "True\n" + "From is_even(x): True\n", + "From lambda: True\n" ] } ], "source": [ "# Example 1\n", - "# def c(x):\n", - "# return x % 2 == 0 #One line function to check if even\n", + "\n", + "def is_even(x):\n", + " return x % 2 == 0 # One line function to check if even\n", + "\n", "a = int(input())\n", - "c = lambda x: x % 2 == 0 # Equivalent lambda function\n", - "print(c(a))\n", + "print(\"From is_even(x):\", is_even(a))\n", + "print(\"From lambda:\", (lambda x: x % 2 == 0)(a)) # Equivalent lambda function\n", "\n", "# Input: 10" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `lambda` function is generally created for use with iterables where the function is applied to several values but at only once (that part of the code).\n", + "\n", + "The usual places include maps, filter and keys for sorting for any iterable. Visit [Lists](DS_Lists.ipynb) or [Tuples](DS_Tuples.ipynb) to know more on them" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -127,8 +163,10 @@ "\n", "A recursive function calls itself repeatedly by dividing the problem into sub problems until the solution is obtained for the smallest sub-problem.\n", "\n", - ">*def* function(paramters1): \n", - "    function(parameters2) -- Recursive calling" + "```python\n", + "def function(paramters1):\n", + " function(parameters2) # Recursive calling\n", + "```" ] }, { @@ -152,10 +190,10 @@ } ], "source": [ - "# Example using factorial\n", + "# Example using factorial (n! = 1 * 2 * 3 ... n) n! = n * (n-1)!\n", "def factorial(n):\n", " if -1\n", + "1\n", "2 * 1 \n", "3 * 2 * 1 \n", "4 * 3 * 2 * 1 \n", "5 * 4 * 3 * 2 * 1 \n", "6 * 5 * 4 * 3 * 2 * 1 \n", "\n", - "720" + "720\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can find the steps in recursion below \n", + "The '|' line indicates the same level of recursive call" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "6\n", + "|\t5\n", + "|\t|\t4\n", + "|\t|\t|\t3\n", + "|\t|\t|\t|\t2\n", + "|\t|\t|\t|\t|\t1\n", + "|\t|\t|\t|\t2\n", + "|\t|\t|\t6\n", + "|\t|\t24\n", + "|\t120\n", + "720\n" + ] + }, + { + "data": { + "text/plain": [ + "720" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# The indent paramter defines the offset of output. This program is to understand recursion only.\n", + "def fact(n, indent=''):\n", + " print(indent, n, sep='')\n", + " if 0 <= n <= 1: return 1\n", + " else:\n", + " fac = n * fact(n-1, indent + \"|\\t\")\n", + " print(indent, fac, sep='')\n", + " return fac\n", + "\n", + "fact(6)" ] }, { @@ -333,6 +427,8 @@ "def add(a, b): # Function Definition - Parameters\n", " print(a, b)\n", " return a+b # returns the sum\n", + "\n", + "\n", "x = int(input())\n", "y = int(input())\n", "print(add(b = x, a = y)) # Function Calling - Keywords are names of params used in definition\n", @@ -448,7 +544,7 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": 2, "metadata": {}, "outputs": [ { @@ -477,7 +573,7 @@ "source": [ "#Example\n", "# Example \n", - "def add(a, *b): # Function Definition - * incicates variable length arguments\n", + "def add(a, *b): # Function Definition - * indicates variable length arguments\n", " print(b)\n", " return a + sum(b) # returns the sum; sum is a built in function that returns sum of elements in an iterable\n", "x = int(input())\n", @@ -510,6 +606,31 @@ "Variable length arguments of the form key = value. Stores the values as key-value mapping or dictionary." ] }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'x': 2, 'y': 3}\n", + "x = 2\n", + "y = 3\n" + ] + } + ], + "source": [ + "#kwargs example\n", + "def kwargs_ex(**a):\n", + " print(a)\n", + " for k, v in a.items():\n", + " print(f\"{k} = {v}\")\n", + "\n", + "kwargs_ex(x=2, y=3)" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -529,7 +650,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 7, "metadata": {}, "outputs": [ { @@ -551,7 +672,10 @@ "Hello\n", "Hello\n", "Hello\n", - "10 23 10 -100\n" + "10 23 10 -100\n", + "Hello\n", + "Hello\n", + "4\n" ] }, { @@ -561,7 +685,7 @@ "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 18\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 19\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 20\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mc\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 21\u001b[0m \u001b[0mprintf\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 22\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 21\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 22\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 23\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mc\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 24\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 25\u001b[0m \u001b[1;31m# Input:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mNameError\u001b[0m: name 'c' is not defined" ] } @@ -586,9 +710,10 @@ " k = 'Hello'\n", " print(k)\n", "print(x,y,s,z)\n", - "print(c)\n", "printf()\n", "print(k)\n", + "print(i)\n", + "print(c)\n", "\n", "# Input:\n", "# 10\n", @@ -597,7 +722,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -637,7 +762,9 @@ "They act as descriptor of function, i.e., they describe the function.\n", "\n", "Calling docstings:\n", - "*function_name.__doc__*" + "```python\n", + "function_name.__doc__\n", + "```" ] }, { @@ -696,7 +823,9 @@ "source": [ "### 1. print: \n", "Syntax:\n", - "`print(values, [end=”\\n”, sep=” ”])`" + "```python\n", + "print(values, end=\"\\n\", sep\" \")\n", + "```" ] }, { @@ -810,7 +939,10 @@ "metadata": {}, "source": [ "### 2. input:\n", - "Syntax: `input(prompt=\"\")`" + "Syntax: \n", + "```python\n", + "input(prompt=\"\")\n", + "```" ] }, { @@ -834,7 +966,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -856,7 +988,10 @@ "metadata": {}, "source": [ "### 3. int:\n", - "Syntax: `int(x, base = 10)`" + "Syntax: \n", + "```python \n", + "int(x, base = 10)\n", + "```" ] }, { @@ -947,7 +1082,10 @@ "metadata": {}, "source": [ "### 4. float:\n", - "Syntax: `float(x = 0)`" + "Syntax: \n", + "```python\n", + "float(x = 0)\n", + "```" ] }, { @@ -1074,6 +1212,91 @@ "\n", "Argument given as a list/tuple is split across required variable. This is called scatter" ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10 23 30 40\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 (23, 30, 40)\n", + "103\n" + ] + } + ], + "source": [ + "#Example\n", + "def add(a, *b): # Function Definition \n", + " print(a, b)\n", + " return a + sum(b) # returns the sum; sum is a built in function that returns sum of elements in an iterable\n", + "\n", + "l = list(map(int, input().split()))\n", + "print(add(*l)) # Function Calling\n", + "\n", + "# Input: 10\n", + "# 23\n", + "# 30\n", + "# 40" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Higher Order Functions or Function Decorators:\n", + "\n", + "A function returning another function is called a higher order function\n", + "\n", + "```python\n", + "def function1(params):\n", + " def function2(params):\n", + " Statements\n", + "\n", + " return function2\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter a num\n", + " 6\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12\n" + ] + } + ], + "source": [ + "def deco(k): # Higher order function / decorator\n", + " def multiple(n):\n", + " return n*k\n", + " return multiple\n", + "\n", + "second_multiple = deco(2)\n", + "n = int(input(\"Enter a num\\n\"))\n", + "print(second_multiple(n))" + ] } ], "metadata": { @@ -1092,7 +1315,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/Generators-checkpoint.ipynb b/.ipynb_checkpoints/Generators-checkpoint.ipynb index 490d86c..31d9114 100644 --- a/.ipynb_checkpoints/Generators-checkpoint.ipynb +++ b/.ipynb_checkpoints/Generators-checkpoint.ipynb @@ -42,12 +42,12 @@ } ], "source": [ - "def my_first_generator():\n", + "def my_first_generator(): # Defining a generator\n", " i = 1\n", " while i<=100:\n", " yield i\n", - " i+=1\n", - "for j in my_first_generator():\n", + " i += 1\n", + "for j in my_first_generator(): # Calling a generator\n", " print(j, end=' ')" ] }, @@ -83,10 +83,116 @@ } ], "source": [ - "gen = (2*i for i in range(10))\n", + "gen = ( 2*i for i in range(10) ) # Definition of a generator\n", "for i in gen:\n", " print(i)" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## next method:\n", + "Returns the next element of the generator.\n", + "\n", + "Syntax: `generator.__next__()`" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n", + "11\n", + "12\n", + "13\n", + "14\n", + "15\n", + "16\n", + "17\n", + "18\n", + "19\n", + "20\n", + "21\n", + "22\n", + "23\n", + "24\n", + "25\n", + "26\n", + "27\n", + "28\n", + "29\n", + "30\n", + "31\n", + "32\n", + "33\n", + "34\n", + "35\n", + "36\n", + "37\n", + "38\n", + "39\n", + "40\n", + "41\n", + "42\n", + "43\n", + "44\n", + "45\n", + "46\n", + "47\n", + "48\n", + "49\n", + "50\n" + ] + } + ], + "source": [ + "def my_first_generator(): # Defining a generator\n", + " i = 1\n", + " while i<=100:\n", + " yield i\n", + " i += 1\n", + "gen = my_first_generator()\n", + "for j in range(50): # Calling a generator\n", + " print(gen.__next__())" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "2\n", + "4\n", + "6\n", + "8\n" + ] + } + ], + "source": [ + "gen = ( 2*i for i in range(10) ) # Definition of a generator\n", + "for i in range(5):\n", + " print(gen.__next__())" + ] } ], "metadata": { diff --git a/.ipynb_checkpoints/Higher_order_functions-checkpoint.py b/.ipynb_checkpoints/Higher_order_functions-checkpoint.py new file mode 100644 index 0000000..ae9c3db --- /dev/null +++ b/.ipynb_checkpoints/Higher_order_functions-checkpoint.py @@ -0,0 +1,8 @@ +def deco(k): # Higher order function / decorator + def multiple(n): + return n*k + return multiple + +second_multiple = deco(2) +n = int(input("Enter a num\n")) +print(second_multiple(n)) \ No newline at end of file diff --git a/.ipynb_checkpoints/Introduction_to_Python_Programming-checkpoint.ipynb b/.ipynb_checkpoints/Introduction_to_Python_Programming-checkpoint.ipynb index ecec7ac..f351ce9 100644 --- a/.ipynb_checkpoints/Introduction_to_Python_Programming-checkpoint.ipynb +++ b/.ipynb_checkpoints/Introduction_to_Python_Programming-checkpoint.ipynb @@ -4,6 +4,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "# Introduction to Python Programming\n", + "\n", "#### Program:\n", "A set of instructions to perform a specific task\n", "#### Programming Language\n", @@ -27,9 +29,9 @@ "Python versions: \n", "1.\t2.x\n", "2.\t3.x \n", - "\n", - "90% match. Small syntax and data changes. \n", - "Latest: Python 3.8.5\n", + " \n", + "Latest: Python 3.9.1\n", + "Preferred 3.8.6\n", "\n", "Things needed in a program:\n", "1.\tInput (i/p)\n", @@ -47,7 +49,10 @@ "source": [ "### Input:\n", "Input from the user is obtained using the input statement \n", - ">Syntax: `input(prompt = \"\")`" + "Syntax: \n", + "```python\n", + "input(prompt = \"\")\n", + "```" ] }, { @@ -76,8 +81,11 @@ "metadata": {}, "source": [ "### Output:\n", - "The output is displayed to the user using the print statement\n", - "> Syntax: `print(values,..., end=”\\n”, sep=” ”)`\n" + "The output is displayed to the user using the print statement \n", + "Syntax: \n", + "```python\n", + "print(values,..., end=\"\\n\", sep=\" \")\n", + "```" ] }, { @@ -126,7 +134,7 @@ "2. Floating point numbers or double (float): 22/7, -0.15\n", "\n", "#### 2. Character (char):\n", - "All characters that are defined under ASCII (American Standard Code For Information Interchange). Look the below chart for the list of characters allowed under ASCII.\n", + "All characters that are defined by Unicode. Look the below chart for the list of characters allowed under ASCII (American Standard Code for Information Interchange) which are most commonly used.\n", "\n", "\n", "\n", @@ -187,12 +195,12 @@ "- Generally, uppercase alphabets are not used in the beginning of a variable name.\n", "\n", "##### Naming Conventions:\n", - "[Naming Convention - Wikipedia article](https://en.wikipedia.org/wiki/Naming_convention_(programming)) \n", + "Naming Convention - Wikipedia article \n", "For Easy readability \n", "- Function or use as name\n", "- first letter in lowercase\n", "- name has Multiple words:\n", - " 1. use space for underscore\n", + " 1. use underscore for space\n", " 2. joint writing with words from second in caps\n", "- No Long names\n", "\n", @@ -230,11 +238,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Keywords or Indentifiers or Reserved words:\n", + "### Keywords or Identifiers or Reserved words:\n", "\n", "Words used for a special purpose in program.\n", "\n", - "E.g: input, print, int, if, for, try, list, etc." + "```python\n", + "Eg: input, print, int, if, for, try, list, etc.\n", + "```" ] }, { @@ -268,7 +278,9 @@ "source": [ "### Documentation Strings or Doc strings:\n", "\n", - "''' ''' , \"\"\" \"\"\" define documentation strings.\n", + "```python\n", + "''' ''' and \"\"\" \"\"\" define documentation strings.\n", + "```\n", "\n", "Brief explanation of code.\n" ] @@ -302,15 +314,17 @@ "\n", "Convert one form of data into another\n", "\n", - "`type()` function gives the data type of a variable\n", + "```python\n", + "type() # function gives the data type of a variable\n", + "```\n", "\n", "|Method|Result|Syntax|\n", "|---|---|---|\n", "|int()|Converts Numeric data into integer|int(x [, base=10])|\n", "|float()|Converts Numeric Data into float|float(x)|\n", "|str()|Converts Data into string|str([x])|\n", - "|ord()|Generates decimal ASCII value of a character|ord(x)|\n", - "|chr()|Returns the ASCII character of given value|chr(x)|\n", + "|ord()|Generates Unicode code point integer value of a character|ord(x)|\n", + "|chr()|Returns the Unicode character of given value|chr(x)|\n", "|oct()|Returns octal value as a string|oct(x)|\n", "|bin()|Returns Binary value as a string|bin(x)|\n", "|hex()|Returns Hexadecimal value as a string|hex(x)|\n", @@ -536,7 +550,9 @@ "metadata": {}, "source": [ "#### 1. Simple formtting\n", - "`print('string', variable)`" + "```python\n", + "print('string', variable)\n", + "```" ] }, { @@ -577,13 +593,16 @@ "1. Integer: %d\n", "2. Float: %f\n", "3. Character: %c\n", - "4. String: %s \n", - "`print('string format_specifier'%(order of variables))`" + "4. String: %s \n", + " \n", + "```python\n", + "print('string format_specifier'%(order of variables))\n", + "```" ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 18, "metadata": {}, "outputs": [ { @@ -611,7 +630,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 20, "metadata": {}, "outputs": [ { @@ -636,7 +655,9 @@ "source": [ "#### 3. Format Method:\n", "Uses `.format()` method \n", - "`print(\"string {order}\".format(variables))`" + "```python \n", + "print(\"string {order}\".format(variables))\n", + "```" ] }, { @@ -658,14 +679,14 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Hello Sooriya, Welcome to Python3.8\n", + "Hello Sooriya, Welcome to 3.8Python\n", "Hello Sooriya, Welcome to Python\n", "Welcome to Python3.8 Sooriya\n" ] @@ -673,7 +694,7 @@ ], "source": [ "string1 = 'Python'\n", - "print(\"Hello {0}, Welcome to {1}{2}\".format(name, string1, ver))\n", + "print(\"Hello {0}, Welcome to {2}{1}\".format(name, string1, ver))\n", "print(\"Hello {}, Welcome to {}\".format(name, string1))\n", "print(\"Welcome to {}{} {}\".format(str1, ver, name))" ] @@ -684,13 +705,15 @@ "source": [ "#### 4. F-strings:\n", "F-strings or formatted strings used to format strings using variables \n", - "`f'string {variable}'` \n", + "```python \n", + "f'string {variable}'\n", + "```\n", "The f-strings came after Python 3.6" ] }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 22, "metadata": {}, "outputs": [ { @@ -732,25 +755,38 @@ "The format method is used to format integers and floats as required.\n", "\n", "#### Integer Formatting:\n", - "Leading zeroes adding to integers\n", + "Leading zeroes adding to integers \n", "Eg: 01 002\n", "##### 1. Format Specifiers:\n", - "`%d` - integer \n", - "`%0nd` - no. of leading zeroes = n - no. of digits in the integer \n", + "```python\n", + "%d - integer \n", + "%0nd - no. of leading zeroes\n", + "```\n", + "= n - no. of digits in the integer\n", "##### 2. format method:\n", - "`format(int_value, format)`\n", + "```python\n", + "format(int_value, format)\n", + "```\n", "##### 3. f-strings:\n", - "`{int_value:0nd}`\n", + "```python\n", + "{int_value:0nd}\n", + "```\n", "#### Float formatting:\n", "Round off decimal places \n", "Eg: 10.1234: 10.12\n", "##### 1. Format Specifiers:\n", - "`%f` - float \n", - "`%.2f` - 2 decimal places\n", + "```python\n", + "%f - float \n", + "%.2f - 2 decimal places\n", + "```\n", "##### 2. format method:\n", - "`format(float_value, format)`\n", + "```python\n", + "format(float_value, format)\n", + "```\n", "##### 3. f-strings:\n", - "`{float_value:.nf}`\n" + "```python\n", + "f\"{float_value:.nf}\"\n", + "```\n" ] }, { @@ -767,7 +803,10 @@ "## Muliple Assignment in one line:\n", "Python allows assignment of different variables in one line.\n", "\n", - "Syntax: `var1, var2, var3, ... = val1, val2, val3, ...`" + "Syntax: \n", + "```python \n", + "var1, var2, var3, ... = val1, val2, val3, ...\n", + "```" ] }, { @@ -811,7 +850,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/Looping_Statements-checkpoint.ipynb b/.ipynb_checkpoints/Looping_Statements-checkpoint.ipynb index 7ee587d..1dbd613 100644 --- a/.ipynb_checkpoints/Looping_Statements-checkpoint.ipynb +++ b/.ipynb_checkpoints/Looping_Statements-checkpoint.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Looping Statements:\n", + "# Looping Statements\n", "Execute a group of lines repeatedly.\n", "\n", "Finite looping is the best practice in programming but infinite looping are done because they are easy at times.\n", @@ -25,8 +25,10 @@ "For loop is used to iterate through a sequence or iterator.\n", "Lists, tuple, dictionary and string.\n", "Syntax:\n", - ">*for* value *in* iterable: \n", - "    Statements" + "```python\n", + "for value in iterable: \n", + " Statements\n", + "```" ] }, { @@ -108,8 +110,11 @@ "#### Range function:\n", "Used to create an sequence/object from *start* to *stop* in *steps*\n", "\n", - "Syntax: *range*(stop) \n", - "*range*(start, stop, [step=1])" + "Syntax: \n", + "```python\n", + "range(stop) \n", + "range(start, stop, [step=1])\n", + "```" ] }, { @@ -226,8 +231,10 @@ "Preferred for variable conditions\n", "\n", "Syntax: \n", - ">*while* condition: \n", - "   Statements" + "```python\n", + "while condition: \n", + " Statements\n", + "```" ] }, { @@ -485,7 +492,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 2, "metadata": {}, "outputs": [ { @@ -567,7 +574,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/Modules_and_Packages-checkpoint.ipynb b/.ipynb_checkpoints/Modules_and_Packages-checkpoint.ipynb new file mode 100644 index 0000000..0766d66 --- /dev/null +++ b/.ipynb_checkpoints/Modules_and_Packages-checkpoint.ipynb @@ -0,0 +1,1336 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Modules and Packages\n", + "Modules are files that contain functions, variables or classes that can be used without redefining them. They're generally written in Python.\n", + "\n", + "Packages are directory or folders which conatin a number of modules or packages in them." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Few built-in Modules are:\n", + "1. \\_\\_builtins\\_\\_\n", + "0. \\_\\_file\\_\\_\n", + "2. math\n", + "3. cmath\n", + "2. sys\n", + "4. os\n", + "5. itertools\n", + "6. string" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The basics of working with module are discussed using a file *prime_generator.py*\n", + "\n", + "Code: \n", + "```python\n", + "from time import *\n", + "from itertools import *\n", + "from math import *\n", + "\n", + "def prime_gen(n):\n", + " num = 2\n", + " while num <= n:\n", + " k = 2\n", + " while k * k <= num:\n", + " if num % k == 0:\n", + " break\n", + " k += 1\n", + " else:\n", + " yield num\n", + " num += 1\n", + "\n", + "prime = 2\n", + "prime_square = 4\n", + "__primeval = 3\n", + "\n", + "if __name__ == '__main__':\n", + " t = time()\n", + " for i in prime_gen(10 ** 2):\n", + " print(i)\n", + " print(time()-t)\n", + "```\n", + "\n", + "Contents:\n", + "1. prime_gen - function or generator \n", + "2. prime - varaiable (constant when imported)\n", + "3. prime_square - variable (constant when imported)\n", + "4. \\_\\_primeval - private value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## import statement:\n", + "The *import* keyword is used to import a module or package.\n", + "\n", + "Syntax: \n", + "```python\n", + "import module_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "import prime_generator\n", + "\n", + "for i in prime_generator.prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## from statement:\n", + "The *from* keyword is used to import a specific set of functions or classes from a module.\n", + "\n", + "Syntax: \n", + "```python\n", + "from module_name import function_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "from prime_generator import prime_gen\n", + "\n", + "for i in prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Importing all the objects from the module:\n", + "To import all the functions or objects, use * .\n", + "\n", + "Syntax: \n", + "```python\n", + "from module_name import *\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "from prime_generator import *\n", + "\n", + "for i in prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## **as** Keyword:\n", + "*as* Keyword is used to have a custom name for imported module or function.\n", + "\n", + "Syntax: \n", + "\n", + "```python\n", + "import moule_name as custom_name\n", + "from module_name import function_name as custom_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "import prime_generator as pg\n", + "\n", + "for i in pg.prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "from prime_generator import prime_gen as pgf\n", + "\n", + "for i in pgf(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## \\_\\_name\\_\\_:\n", + "It returns the name of the module without the extension. If called for main executing program (main module), it returns '\\_\\_main\\_\\_'\n", + "\n", + "Syntax: \n", + "```python\n", + "module_name.__name__\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "prime_generator\n", + "__main__\n" + ] + } + ], + "source": [ + "import prime_generator as pg\n", + "\n", + "print(pg.__name__)\n", + "print(__name__)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## dir method:\n", + "\n", + "Returns the list of attributes (that are relevant) of an object or a module. By default, it gives the details of main module.\n", + "\n", + "Syntax: \n", + "```python\n", + "dir([object])\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__primeval', '__spec__', 'accumulate', 'acos', 'acosh', 'altzone', 'asctime', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'chain', 'comb', 'combinations', 'combinations_with_replacement', 'compress', 'copysign', 'cos', 'cosh', 'count', 'ctime', 'cycle', 'daylight', 'degrees', 'dist', 'dropwhile', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'filterfalse', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'get_clock_info', 'gmtime', 'groupby', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'islice', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'localtime', 'log', 'log10', 'log1p', 'log2', 'mktime', 'modf', 'monotonic', 'monotonic_ns', 'nan', 'nextafter', 'perf_counter', 'perf_counter_ns', 'perm', 'permutations', 'pi', 'pow', 'prime', 'prime_gen', 'prime_square', 'process_time', 'process_time_ns', 'prod', 'product', 'radians', 'remainder', 'repeat', 'sin', 'sinh', 'sleep', 'sqrt', 'starmap', 'strftime', 'strptime', 'struct_time', 'takewhile', 'tan', 'tanh', 'tau', 'tee', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'trunc', 'tzname', 'ulp', 'zip_longest']\n", + "\n", + "['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']\n", + "\n", + "['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'prime_generator', 'quit']\n" + ] + } + ], + "source": [ + "import prime_generator\n", + "\n", + "print(dir(prime_generator))\n", + "print()\n", + "print(dir(prime_generator.prime_gen))\n", + "print()\n", + "print(dir())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## namespace:\n", + "\n", + "A container that has a list of names (objects) defined in a module. It is the place where python searches for objects defined and used in a function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Global, Local and Built-in Namespaces\n", + "\n", + "### Global:\n", + "Namespace containing values defined throughout a file or module (globally)\n", + "\n", + "### Local:\n", + "Namespace containing values defined in a part of a file or module (Locally)\n", + "\n", + "### Builtin:\n", + "Namespace containing values common for all python file.\n", + "\n", + "## Order of Search:\n", + "1. Local\n", + "2. Global\n", + "3. Builtin" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Packages:\n", + "Directory or folder containing a number of modules and subpackages.\n", + "\n", + "It contains '\\_\\_init\\_\\_.py' file which defines the modules that can be imported from the package.\n", + "\n", + "### Importing a module from package: \n", + "```python\n", + "import package_name.module_name\n", + "import package_name.module_name as custom_name\n", + "```\n", + "\n", + "### Import a specific object from a module:\n", + "```python\n", + "from package_name.module_name import object_name\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Builtins:\n", + "\n", + "\\_\\_builtins\\_\\_ module contains the list of methods and variables that are standard definitions in Python." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ArithmeticError\n", + "AssertionError\n", + "AttributeError\n", + "BaseException\n", + "BlockingIOError\n", + "BrokenPipeError\n", + "BufferError\n", + "BytesWarning\n", + "ChildProcessError\n", + "ConnectionAbortedError\n", + "ConnectionError\n", + "ConnectionRefusedError\n", + "ConnectionResetError\n", + "DeprecationWarning\n", + "EOFError\n", + "Ellipsis\n", + "EnvironmentError\n", + "Exception\n", + "False\n", + "FileExistsError\n", + "FileNotFoundError\n", + "FloatingPointError\n", + "FutureWarning\n", + "GeneratorExit\n", + "IOError\n", + "ImportError\n", + "ImportWarning\n", + "IndentationError\n", + "IndexError\n", + "InterruptedError\n", + "IsADirectoryError\n", + "KeyError\n", + "KeyboardInterrupt\n", + "LookupError\n", + "MemoryError\n", + "ModuleNotFoundError\n", + "NameError\n", + "None\n", + "NotADirectoryError\n", + "NotImplemented\n", + "NotImplementedError\n", + "OSError\n", + "OverflowError\n", + "PendingDeprecationWarning\n", + "PermissionError\n", + "ProcessLookupError\n", + "RecursionError\n", + "ReferenceError\n", + "ResourceWarning\n", + "RuntimeError\n", + "RuntimeWarning\n", + "StopAsyncIteration\n", + "StopIteration\n", + "SyntaxError\n", + "SyntaxWarning\n", + "SystemError\n", + "SystemExit\n", + "TabError\n", + "TimeoutError\n", + "True\n", + "TypeError\n", + "UnboundLocalError\n", + "UnicodeDecodeError\n", + "UnicodeEncodeError\n", + "UnicodeError\n", + "UnicodeTranslateError\n", + "UnicodeWarning\n", + "UserWarning\n", + "ValueError\n", + "Warning\n", + "WindowsError\n", + "ZeroDivisionError\n", + "__IPYTHON__\n", + "__build_class__\n", + "__debug__\n", + "__doc__\n", + "__import__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "abs\n", + "all\n", + "any\n", + "ascii\n", + "bin\n", + "bool\n", + "breakpoint\n", + "bytearray\n", + "bytes\n", + "callable\n", + "chr\n", + "classmethod\n", + "compile\n", + "complex\n", + "copyright\n", + "credits\n", + "delattr\n", + "dict\n", + "dir\n", + "display\n", + "divmod\n", + "enumerate\n", + "eval\n", + "exec\n", + "filter\n", + "float\n", + "format\n", + "frozenset\n", + "get_ipython\n", + "getattr\n", + "globals\n", + "hasattr\n", + "hash\n", + "help\n", + "hex\n", + "id\n", + "input\n", + "int\n", + "isinstance\n", + "issubclass\n", + "iter\n", + "len\n", + "license\n", + "list\n", + "locals\n", + "map\n", + "max\n", + "memoryview\n", + "min\n", + "next\n", + "object\n", + "oct\n", + "open\n", + "ord\n", + "pow\n", + "print\n", + "property\n", + "range\n", + "repr\n", + "reversed\n", + "round\n", + "set\n", + "setattr\n", + "slice\n", + "sorted\n", + "staticmethod\n", + "str\n", + "sum\n", + "super\n", + "tuple\n", + "type\n", + "vars\n", + "zip\n" + ] + } + ], + "source": [ + "builtin = dir(__builtins__)\n", + "for i in builtin:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## \\_\\_file\\_\\_ module:\n", + "\n", + "It contains the list of builtin variables and functions that can be used in the current file." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### contents:\n", + "\\_\\_add\\_\\_ \n", + "\\_\\_class\\_\\_ \n", + "\\_\\_contains\\_\\_ \n", + "\\_\\_delattr\\_\\_ \n", + "\\_\\_dir\\_\\_ \n", + "\\_\\_doc\\_\\_ \n", + "\\_\\_eq\\_\\_ \n", + "\\_\\_format\\_\\_ \n", + "\\_\\_ge\\_\\_ \n", + "\\_\\_getattribute\\_\\_ \n", + "\\_\\_getitem\\_\\_ \n", + "\\_\\_getnewargs\\_\\_ \n", + "\\_\\_gt\\_\\_ \n", + "\\_\\_hash\\_\\_ \n", + "\\_\\_init\\_\\_ \n", + "\\_\\_init_subclass\\_\\_ \n", + "\\_\\_iter\\_\\_ \n", + "\\_\\_le\\_\\_ \n", + "\\_\\_len\\_\\_ \n", + "\\_\\_lt\\_\\_ \n", + "\\_\\_mod\\_\\_ \n", + "\\_\\_mul\\_\\_ \n", + "\\_\\_ne\\_\\_ \n", + "\\_\\_new\\_\\_ \n", + "\\_\\_reduce\\_\\_ \n", + "\\_\\_reduce_ex\\_\\_ \n", + "\\_\\_repr\\_\\_ \n", + "\\_\\_rmod\\_\\_ \n", + "\\_\\_rmul\\_\\_ \n", + "\\_\\_setattr\\_\\_ \n", + "\\_\\_sizeof\\_\\_ \n", + "\\_\\_str\\_\\_ \n", + "\\_\\_subclasshook\\_\\_ \n", + "capitalize \n", + "casefold \n", + "center \n", + "count \n", + "encode \n", + "endswith \n", + "expandtabs \n", + "find \n", + "format \n", + "format_map \n", + "index \n", + "isalnum \n", + "isalpha \n", + "isascii \n", + "isdecimal \n", + "isdigit \n", + "isidentifier \n", + "islower \n", + "isnumeric \n", + "isprintable \n", + "isspace \n", + "istitle \n", + "isupper \n", + "join \n", + "ljust \n", + "lower \n", + "lstrip \n", + "maketrans \n", + "partition \n", + "replace \n", + "rfind \n", + "rindex \n", + "rjust \n", + "rpartition \n", + "rsplit \n", + "rstrip \n", + "split \n", + "splitlines \n", + "startswith \n", + "strip \n", + "swapcase \n", + "title \n", + "translate \n", + "upper \n", + "zfill " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Private in modules:\n", + "\n", + "Objects can be restricted to usage when running as a main module. They cannot be imported when importing the complete module using ' * '.\n", + "\n", + "They start and end with double underscores, \\_\\_" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n" + ] + } + ], + "source": [ + "import prime_generator as pg\n", + "\n", + "print(pg.__primeval)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name '__primeval' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mprime_generator\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[1;33m*\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0m__primeval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mNameError\u001b[0m: name '__primeval' is not defined" + ] + } + ], + "source": [ + "from prime_generator import *\n", + "\n", + "print(__primeval)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## globals(), locals() and reload()\n", + "\n", + "globals - returns the list of objects that can be accessed globally from that point.\n", + "\n", + "locals - returns the list of objects that can be accessed locally from that point.\n", + "\n", + "reload - reloads the given module. (imported from impotlib module)\n", + "\n", + "Syntax: \n", + "```python\n", + "reload(module_name)\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## math:\n", + "This module contains list of all mathematical functions." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__doc__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "acos\n", + "acosh\n", + "asin\n", + "asinh\n", + "atan\n", + "atan2\n", + "atanh\n", + "ceil\n", + "comb\n", + "copysign\n", + "cos\n", + "cosh\n", + "degrees\n", + "dist\n", + "e\n", + "erf\n", + "erfc\n", + "exp\n", + "expm1\n", + "fabs\n", + "factorial\n", + "floor\n", + "fmod\n", + "frexp\n", + "fsum\n", + "gamma\n", + "gcd\n", + "hypot\n", + "inf\n", + "isclose\n", + "isfinite\n", + "isinf\n", + "isnan\n", + "isqrt\n", + "ldexp\n", + "lgamma\n", + "log\n", + "log10\n", + "log1p\n", + "log2\n", + "modf\n", + "nan\n", + "perm\n", + "pi\n", + "pow\n", + "prod\n", + "radians\n", + "remainder\n", + "sin\n", + "sinh\n", + "sqrt\n", + "tan\n", + "tanh\n", + "tau\n", + "trunc\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "print(*dir(math), sep='\\n')" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.5707963267948966\n", + "1.5707963267948966\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "print(math.pi/2)\n", + "print(math.asin(1))\n", + "# 1.570796... = pi/2" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "22\n", + "21\n" + ] + } + ], + "source": [ + "# 21.33 ceil - 22\n", + "# 21.33 floor - 21\n", + "# 21, 21.33, 22\n", + "print(math.ceil(21.33))\n", + "print(math.floor(21.33))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "8.0" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "math.pow(2, 3) # 2 ** 3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$\\mathit{^5P_2}$" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "math.perm(5, 2) # 5P2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$\\mathit{^5C_2}$" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "math.comb(5, 2) # 5C2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## cmath:\n", + "Like math, used to work with complex numbers." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__doc__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "acos\n", + "acosh\n", + "asin\n", + "asinh\n", + "atan\n", + "atanh\n", + "cos\n", + "cosh\n", + "e\n", + "exp\n", + "inf\n", + "infj\n", + "isclose\n", + "isfinite\n", + "isinf\n", + "isnan\n", + "log\n", + "log10\n", + "nan\n", + "nanj\n", + "phase\n", + "pi\n", + "polar\n", + "rect\n", + "sin\n", + "sinh\n", + "sqrt\n", + "tan\n", + "tanh\n", + "tau\n" + ] + } + ], + "source": [ + "import cmath\n", + "\n", + "print(*dir(cmath), sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## sys:\n", + "\n", + "Work with program execution and system." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__breakpointhook__\n", + "__displayhook__\n", + "__doc__\n", + "__excepthook__\n", + "__interactivehook__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "__stderr__\n", + "__stdin__\n", + "__stdout__\n", + "__unraisablehook__\n", + "_base_executable\n", + "_clear_type_cache\n", + "_current_frames\n", + "_debugmallocstats\n", + "_enablelegacywindowsfsencoding\n", + "_framework\n", + "_getframe\n", + "_git\n", + "_home\n", + "_xoptions\n", + "addaudithook\n", + "api_version\n", + "argv\n", + "audit\n", + "base_exec_prefix\n", + "base_prefix\n", + "breakpointhook\n", + "builtin_module_names\n", + "byteorder\n", + "call_tracing\n", + "callstats\n", + "copyright\n", + "displayhook\n", + "dllhandle\n", + "dont_write_bytecode\n", + "exc_info\n", + "excepthook\n", + "exec_prefix\n", + "executable\n", + "exit\n", + "flags\n", + "float_info\n", + "float_repr_style\n", + "get_asyncgen_hooks\n", + "get_coroutine_origin_tracking_depth\n", + "getallocatedblocks\n", + "getcheckinterval\n", + "getdefaultencoding\n", + "getfilesystemencodeerrors\n", + "getfilesystemencoding\n", + "getprofile\n", + "getrecursionlimit\n", + "getrefcount\n", + "getsizeof\n", + "getswitchinterval\n", + "gettrace\n", + "getwindowsversion\n", + "hash_info\n", + "hexversion\n", + "implementation\n", + "int_info\n", + "intern\n", + "is_finalizing\n", + "maxsize\n", + "maxunicode\n", + "meta_path\n", + "modules\n", + "path\n", + "path_hooks\n", + "path_importer_cache\n", + "platform\n", + "prefix\n", + "ps1\n", + "ps2\n", + "ps3\n", + "pycache_prefix\n", + "set_asyncgen_hooks\n", + "set_coroutine_origin_tracking_depth\n", + "setcheckinterval\n", + "setprofile\n", + "setrecursionlimit\n", + "setswitchinterval\n", + "settrace\n", + "stderr\n", + "stdin\n", + "stdout\n", + "thread_info\n", + "unraisablehook\n", + "version\n", + "version_info\n", + "warnoptions\n", + "winver\n" + ] + } + ], + "source": [ + "import sys\n", + "\n", + "print(*dir(sys), sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## os:\n", + "works with operating system" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "DirEntry\n", + "F_OK\n", + "MutableMapping\n", + "O_APPEND\n", + "O_BINARY\n", + "O_CREAT\n", + "O_EXCL\n", + "O_NOINHERIT\n", + "O_RANDOM\n", + "O_RDONLY\n", + "O_RDWR\n", + "O_SEQUENTIAL\n", + "O_SHORT_LIVED\n", + "O_TEMPORARY\n", + "O_TEXT\n", + "O_TRUNC\n", + "O_WRONLY\n", + "P_DETACH\n", + "P_NOWAIT\n", + "P_NOWAITO\n", + "P_OVERLAY\n", + "P_WAIT\n", + "PathLike\n", + "R_OK\n", + "SEEK_CUR\n", + "SEEK_END\n", + "SEEK_SET\n", + "TMP_MAX\n", + "W_OK\n", + "X_OK\n", + "_AddedDllDirectory\n", + "_Environ\n", + "__all__\n", + "__builtins__\n", + "__cached__\n", + "__doc__\n", + "__file__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "_check_methods\n", + "_execvpe\n", + "_exists\n", + "_exit\n", + "_fspath\n", + "_get_exports_list\n", + "_putenv\n", + "_unsetenv\n", + "_wrap_close\n", + "abc\n", + "abort\n", + "access\n", + "add_dll_directory\n", + "altsep\n", + "chdir\n", + "chmod\n", + "close\n", + "closerange\n", + "cpu_count\n", + "curdir\n", + "defpath\n", + "device_encoding\n", + "devnull\n", + "dup\n", + "dup2\n", + "environ\n", + "error\n", + "execl\n", + "execle\n", + "execlp\n", + "execlpe\n", + "execv\n", + "execve\n", + "execvp\n", + "execvpe\n", + "extsep\n", + "fdopen\n", + "fsdecode\n", + "fsencode\n", + "fspath\n", + "fstat\n", + "fsync\n", + "ftruncate\n", + "get_exec_path\n", + "get_handle_inheritable\n", + "get_inheritable\n", + "get_terminal_size\n", + "getcwd\n", + "getcwdb\n", + "getenv\n", + "getlogin\n", + "getpid\n", + "getppid\n", + "isatty\n", + "kill\n", + "linesep\n", + "link\n", + "listdir\n", + "lseek\n", + "lstat\n", + "makedirs\n", + "mkdir\n", + "name\n", + "open\n", + "pardir\n", + "path\n", + "pathsep\n", + "pipe\n", + "popen\n", + "putenv\n", + "read\n", + "readlink\n", + "remove\n", + "removedirs\n", + "rename\n", + "renames\n", + "replace\n", + "rmdir\n", + "scandir\n", + "sep\n", + "set_handle_inheritable\n", + "set_inheritable\n", + "spawnl\n", + "spawnle\n", + "spawnv\n", + "spawnve\n", + "st\n", + "startfile\n", + "stat\n", + "stat_result\n", + "statvfs_result\n", + "strerror\n", + "supports_bytes_environ\n", + "supports_dir_fd\n", + "supports_effective_ids\n", + "supports_fd\n", + "supports_follow_symlinks\n", + "symlink\n", + "sys\n", + "system\n", + "terminal_size\n", + "times\n", + "times_result\n", + "truncate\n", + "umask\n", + "uname_result\n", + "unlink\n", + "urandom\n", + "utime\n", + "waitpid\n", + "walk\n", + "write\n" + ] + } + ], + "source": [ + "import os\n", + "print(*dir(os), sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## itertools:\n", + "\n", + "A module containing iterators for efficient looping" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__doc__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "_grouper\n", + "_tee\n", + "_tee_dataobject\n", + "accumulate\n", + "chain\n", + "combinations\n", + "combinations_with_replacement\n", + "compress\n", + "count\n", + "cycle\n", + "dropwhile\n", + "filterfalse\n", + "groupby\n", + "islice\n", + "permutations\n", + "product\n", + "repeat\n", + "starmap\n", + "takewhile\n", + "tee\n", + "zip_longest\n" + ] + } + ], + "source": [ + "import itertools\n", + "\n", + "print(*dir(itertools), sep='\\n')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/.ipynb_checkpoints/OOPS-checkpoint.html b/.ipynb_checkpoints/OOPS-checkpoint.html new file mode 100644 index 0000000..c56ac93 --- /dev/null +++ b/.ipynb_checkpoints/OOPS-checkpoint.html @@ -0,0 +1,14690 @@ + + + + + +OOPS + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.ipynb_checkpoints/OOPS-checkpoint.ipynb b/.ipynb_checkpoints/OOPS-checkpoint.ipynb new file mode 100644 index 0000000..5844223 --- /dev/null +++ b/.ipynb_checkpoints/OOPS-checkpoint.ipynb @@ -0,0 +1,440 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Object Oriented Programming - Part 1\n", + "### OOP:\n", + "\n", + "Object Oriented Programming or OOP is working with classes and objects. It involves interaction between objects having various attributes.\n", + "\n", + "Python is a object oriented programming language. This means that all the types are representation or instance of a type class." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Components:\n", + "1. Class\n", + "2. Object\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Class:\n", + "\n", + "It is a structure, a blueprint or a building block (a code block) representing or defining the attributes (features and behaviour) of similar parameters.\n", + "\n", + "### Definition:\n", + "Using `class` keyword.\n", + "Name of a class should start with an uppercase letter.\n", + "\n", + "Syntax: \n", + "```python\n", + "class Class_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Students:\n", + " roll_no = int()\n", + " name = str()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Object:\n", + "\n", + "It is an instance of a class.\n", + "\n", + "Syntax: \n", + "```python\n", + "obj_name = Class_name()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "student1 = Students() # creating a new object\n", + "\n", + "student1.roll_no = 1\n", + "student1.name = 'Prabhu'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Prabhu\n", + "1\n" + ] + } + ], + "source": [ + "print(student1.name)\n", + "print(student1.roll_no)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## *self* Keyword:\n", + "\n", + "Calls the attributes for current instance or object.\n", + "\n", + "Syntax: \n", + "```python\n", + "self.attribute_name\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining attributes and behavior in a class\n", + "\n", + "An object is generally defined by the follwing:\n", + "1. Fields (variables) or Attributes\n", + "2. Methods (functions) or Behavior\n", + "\n", + "### Fields\n", + "The `fields` are the variables or containers that store data used and related to an object/Class\n", + "\n", + "Types: \n", + "1. Instance fields\n", + "2. Class or static fields\n", + "\n", + "#### Instance fields:\n", + "The instance fields are variables that are associated with an object, an instance of the class.\n", + "\n", + "The data they have may vary from object to object and are independent. The field of one instance cannot be accessed by the other. \n", + "The instance variables are accessed as follows:\n", + "```python\n", + "# Inside the class using `self` keyword\n", + "self.instance_variable\n", + "\n", + "# Outside the class using the object name\n", + "object_name.instance_variable\n", + "```\n", + "\n", + "#### Class fields:\n", + "The class variables are variables that are common throughout the instances of the defined class and can be accessed by all of them.\n", + "\n", + "Modifying data in one object changes it for all the present instances. \n", + "They are accessed inside and outside the class definition as follows:\n", + "```python\n", + "# Using class name to access static variables\n", + "Class_name.class_variable\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Prabhu\n", + "Mano\n", + "2\n" + ] + } + ], + "source": [ + "class Student_details:\n", + " student_count = 0\n", + " def __init__(self, name):\n", + " self.name = name # Instance variable\n", + " Student_details.student_count += 1 # Class Variable\n", + "\n", + "s = Student_details(\"Prabhu\")\n", + "print(s.name) # Instance variable\n", + "s1 = Student_details(\"Mano\")\n", + "print(s1.name) # Instance variable\n", + "print(Student_details.student_count) # Class variable" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Methods\n", + "\n", + "The `methods` are block of code that, like functions, execute a specific task\n", + "\n", + "Though a method and function are defined in the same way, they have differences.\n", + "\n", + "A **function** is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.\n", + "\n", + "A **method** is a piece of code that is called by a name that is associated with an object. \n", + "\n", + "In most respects it is identical to a function except for two key differences:\n", + "\n", + "1. A method is implicitly passed the object on which it was called.\n", + "2. A method is able to operate on data that is contained within the class \n", + "\n", + "(remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).\n", + "\n", + "Source: [What's the difference between a method and a function? - StackOverflow](https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function#155655)\n", + "\n", + "Types:\n", + "\n", + "1. Instance methods\n", + "2. Static methods\n", + "\n", + "#### Instance methods\n", + "\n", + "Instance methods are methods/behavior that are associated with objects. When an object calls one of its instnace methods, the instance method gets implicitly passed object and uses the data it gets with other required parameters to do the task. \n", + "Definition and access:\n", + "\n", + "```python\n", + "# Definition\n", + "def instance_method(self[, ...]): # the self keyword indicates the implicit passing of the object\n", + " # Statements\n", + "\n", + "# access inside the class (in another instance method)\n", + "self.instance_method(...)\n", + "\n", + "# Access outside the class\n", + "obj.instance_method(...)\n", + "```\n", + "\n", + "***Note:*** It is to be noted that an instance method can be called only inside another instance method\n", + "\n", + "#### Static or Class method\n", + "\n", + "A static method is a method that is common for all objects. It is equivalent of function being defined outside the class.\n", + "\n", + "A static method is identified by the decorator `@staticmethod` and has implicit object passing using `self` keyword.\n", + "\n", + "Definition and Access:\n", + "\n", + "```python\n", + "@staticmethod\n", + "def class_method([...]):\n", + " #Statement(s)\n", + "\n", + "# accessing the method using class name\n", + "Class_name.class_method([...])\n", + "```\n", + "The static method can be called inside another static method or instance method(s)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Constructor:\n", + "A method that executes a set of code whenever a new object/instance is created.\n", + "\n", + "Defined as `__new__()`. Generally, this is not defined/overridden and follows the default definition as in the `object` class\n", + "\n", + "```python\n", + "def __new__(cls, *args, **kwargs):\n", + " # Custom constructor\n", + "```\n", + "\n", + "### Initializer:\n", + "An instance method that initializes the object (instance) created by call with the parameters passed. \n", + "\n", + "The `__new__()` method calls this automatically.\n", + "\n", + "Defined as `__init__()`.\n", + "\n", + "```python\n", + "def __init__(self, *args, **kwargs):\n", + " # Statements for object Initialization\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "class Student:\n", + " def __init__(self): # default constructor\n", + " self.roll_no = 0\n", + " self.name = 'Name'\n", + "# print('__init__ file')\n", + " \n", + " def study(self):\n", + " print('Studying....')" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__init__ file\n", + "Roll No: 1, Name: Ravi\n" + ] + } + ], + "source": [ + "st1 = Student()\n", + "st1.roll_no = 1\n", + "st1.name = 'Ravi'\n", + "print(f'Roll No: {st1.roll_no}, Name: {st1.name}')" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "class Student_details:\n", + " def __init__(self, rn = 0, st_name = 'Name'): # Parametric Constructor\n", + " self.roll_no = rn\n", + " self.name = st_name\n", + " # print('__init__ file')\n", + " \n", + " def study(self):\n", + " print('Studying....')\n", + " @staticmethod\n", + " def work():\n", + " print(\"Working...\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Roll No: 2, Name: Rahul\n", + "Working...\n" + ] + } + ], + "source": [ + "st2 = Student_details(2, 'Rahul')\n", + "print(f'Roll No: {st2.roll_no}, Name: {st2.name}')\n", + "Student_details.work()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## destructor:\n", + "Delete the current instance of class or object. It has default definition in the object Base class\n", + "\n", + "Use `__del__()` method to override it\n", + "\n", + "```python\n", + "def __del__(self, *args, **kwargs):\n", + " # Custom destructor\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Some other methods:\n", + "\n", + "1. \\_\\_repr\\_\\_ - String representation\n", + "2. \\_\\_cmp\\_\\_ - Compare two objects\n", + "3. \\_\\_len\\_\\_ - length of object\n", + "4. \\_\\_lt\\_\\_ - less than\n", + "7. \\_\\_le\\_\\_ - less than or equal\n", + "8. \\_\\_gt\\_\\_ - greater than\n", + "9. \\_\\_ge\\_\\_ - greater than or equal\n", + "10. \\_\\_ne\\_\\_ - not equal\n", + "0. \\_\\_eq\\_\\_ - equal\n", + "5. \\_\\_getitem\\_\\_ - get a key from a iterable\n", + "6. \\_\\_setitem\\_\\_ - set a value to the given key of iterable" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Private variables and methods:\n", + "\n", + "Start with \\_\\_\n", + "\n", + "E.g.: \\_\\_var, \\_\\_method\n", + "\n", + "It is advised for best programming practice to avoid calling private attributes outside the class. \n", + "But if needed, use the following syntax:\n", + "\n", + "```python\n", + "obj._classname__attribute\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Check the complete example [OOPS.py](OOPS.py) \n", + "\n", + "Ignore the imports. They have been used to provide hinting about the types of each variable" + ] + } + ], + "metadata": { + "ipub": { + "subtitle": "Object Oriented Programming - Part 1/2", + "title": "Object Oriented Programming - Part 1", + "toc": true + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/.ipynb_checkpoints/OOPS-checkpoint.py b/.ipynb_checkpoints/OOPS-checkpoint.py new file mode 100644 index 0000000..61dfdb5 --- /dev/null +++ b/.ipynb_checkpoints/OOPS-checkpoint.py @@ -0,0 +1,66 @@ +class Student: + obj_count = 0 + stud_list = dict() + + def __init__(self, rn=0, st_name="Name", *clubs): # Parametric Constructor + Student.obj_count += 1 + self.roll_no = rn + self.name = st_name + self.club = clubs + Student.stud_list[rn] = st_name +# {roll_no: st_name} + + def study(self): + print(f"{self.name} is Studying....") + + def wake(self): + self.study() + return "Woke" + + def __del__(self): # destructor + Student.obj_count -= 1 + Student.stud_list.pop(self.roll_no) + + def __repr__(self): + return f"Roll no.: {self.roll_no} \nName: {self.name}\n" f"Clubs: {self.club}" + + def __lt__(self, obj): + return self.name < obj.name + + def __le__(self, obj): + return self.name <= obj.name + + def __gt__(self, obj): + return self.name > obj.name + + def __ge__(self, obj): + return self.name >= obj.name + + def __ne__(self, obj): + return self.name != obj.name + + def __eq__(self, obj): + return self.name == obj.name + + def __getitem__(self, key): + return self.club[key - 1] + + def __setitem__(self, key, value): + self.club[key - 1] = value + + # getter + @property + def roll_no(self): + # print('Getter called') + return self.__roll_no + + # setter + @roll_no.setter + def roll_no(self, rn): + # print('Setter called') + self.__roll_no = rn + + +# Object 1 +st1 = Student(1, "Prabhu", "Coding Club", "Robotics Club") +print(st1.wake()) diff --git a/.ipynb_checkpoints/Practice_code1-checkpoint.html b/.ipynb_checkpoints/Practice_code1-checkpoint.html new file mode 100644 index 0000000..aeca1b8 --- /dev/null +++ b/.ipynb_checkpoints/Practice_code1-checkpoint.html @@ -0,0 +1,14620 @@ + + + + + +Practice_code1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.ipynb_checkpoints/Practice_code1-checkpoint.ipynb b/.ipynb_checkpoints/Practice_code1-checkpoint.ipynb index 6164989..18eafcc 100644 --- a/.ipynb_checkpoints/Practice_code1-checkpoint.ipynb +++ b/.ipynb_checkpoints/Practice_code1-checkpoint.ipynb @@ -40,16 +40,14 @@ "\n", ">Sample 1: \n", "I/p: \n", - "Chandru \n", - "19 \n", + "Chandru 19 \n", "O/p: \n", "Chandru \n", "19 \n", "\n", ">Sample 2: \n", "I/p: \n", - "Prabhu \n", - "20 \n", + "Prabhu 20 \n", "O/p: \n", "Prabhu \n", "20 \n" @@ -395,7 +393,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/.ipynb_checkpoints/Practice_code1-checkpoint.md b/.ipynb_checkpoints/Practice_code1-checkpoint.md new file mode 100644 index 0000000..2bd2a7d --- /dev/null +++ b/.ipynb_checkpoints/Practice_code1-checkpoint.md @@ -0,0 +1,334 @@ +This file contains practice question for [Introduction to Python programming](Introduction_to_Python_Programming.ipynb) (input ad output) + +Try working online at: +[Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) +[Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) + +--- + +**Q1:** Write a program to print 'Hello World' + +--- + +**Q2:** Write a program to get Name from the user and print it. +>**Sample 1:** +I/p: Chandru +O/p: Chandru + +
+>**Sample 2:** +I/p: Prabhu +O/p: Prabhu + +--- + +**Q3:** Write a program to get Name and age from user and print it. + +>**Sample 1:** +I/p: +Chandru 19 +O/p: +Chandru +19 + +
+>**Sample 2:** +I/p: +Prabhu 20 +O/p: +Prabhu +20 + +--- + +**Q4:** Write a program to get two numbers from user and print their sum +>**Sample 1:** +I/p: +12 +12 +O/p: +24 + +
+>**Sample 2:** +I/p: +10 +15 +O/p: +25 + +--- + +**Q5:** Write a program to get two numbers and perform all arithmetic operations on them. + +--- + +**Q6:** (Update of **Q4**) +Print formatted output +>**Sample 1:** +I/p: +12 +12 +O/p: +Sum of 12 and 12 is 24 + +
+>**Sample 2:** +I/p: +10 +15 +O/p: +Sum of 10 and 15 is 25 + +--- + +**Q6:** (Update of **Q4**) +Print formatted output +>**Sample 1:** +I/p: +12 +12 +O/p: +Sum of 12 and 12 is 24 + +
+>**Sample 2:** +I/p: +10 +15 +O/p: +Sum of 10 and 15 is 25 + +--- + +**Q7:** Write a program to get name from the user and wish them Good Morning +>**Sample:** +I/p: Jenyhin +O/p: Good Morning, Jenyhin + +--- + +**Q8:** Write a program to get the side of the square and print its perimeter +$\text{Perimeter of a square} = 4 \times \rm{side}$ +>**Sample 1:** +I/p: 4 +O/p: 16 + +
+>**Sample 2:** +I/p: 22 +O/p: 88 + +--- + +**Q9:** Write a program to get the side of the square and print its area +$\text{Area of square} = \rm{side} \times \rm{side}$ +>**Sample 1:** +I/p: 4 +O/p: 16 + +
+>**Sample 2:** +I/p: 22 +O/p: 484 + +--- + +**Q10:** Write a program to get the length and breadth of a rectangle and print its perimeter +$\text{Perimeter of a rectangle} = 2 \times \rm{(length + breadth)}$ +>**Sample 1:** +I/p: +4
+4 +O/p: 16 + +
+>**Sample 2:** +I/p: +22 +21 +O/p: 86 + +--- + +**Q11:** Write a program to get the length and breadth of a rectangle and print its area +$\text{Area of a rectangle} = \text{length} \times \text{breadth}$ +>**Sample 1:** +I/p: +4
+4 +O/p: 16 + +
+>**Sample 2:** +I/p: +22 +21 +O/p: 462 + +--- + +**Q12:** Write a program to get the number of sides and length of each side of a regular polygon and print its perimeter. +$\text{Perimeter} = \text{number of sides} \times \text{length of one side}$ +>**Sample 1:** +I/p: +8
+4 +O/p: 32 + +
+>**Sample 2:** +I/p: +7
+21 +O/p: 147 + +--- + +**Q13:** Write a program to get the length and height of a right triangle and print its area. +$\text{Area of right triangle} = \dfrac{1}{2} \times \rm{base} \times \rm{height}$ +>**Sample 1:** +I/p: +4
+4 +O/p: 8.0 + +
+>**Sample 2:** +I/p: +22 +21 +O/p: 231.0 + +--- + +**Q14:** Write a program to get the radius of a circle and print its perimeter rounded off to 3 decimal places. (Take $\pi = 3.14159$) +$\text{Perimeter of a circle} = 2\pi \times \rm{radius}$ +>**Sample 1:** +I/p: +4
+O/p: 25.133 + +
+>**Sample 2:** +I/p: +22 +O/p: 138.230 + +--- + +**Q15:** Write a program to get the radius of a circle and print its area rounded off to 3 decimal places. (Take $\pi = 3.14159$) +$\text{Area of a circle} = \pi \times \rm{radius}^2$ +>**Sample 1:** +I/p: +4
+O/p: 50.265 + +>**Sample 2:** +I/p: +21 +O/p: 1385.442 + +--- + +**Q16:** Write a program to get the sides of a triangle and print its area using Heron's Formula rounded off to 3 decimal places. +$\text{Area of right triangle} = \sqrt{s \times (s-a)\times(s-b)\times(s-c)}$ +$\rm{where},$ +$s = \text{Semi-Perimeter} = \dfrac{\text{Perimter of triangle}}{2}$ +$a, ~b, ~c = \text{Sides of the triangle}$ +>**Sample 1:** +I/p: +3
+4
+5 +O/p: 6.0 + +>**Sample 2:** +I/p: +12 +21 +30 +O/p: 98.359 + +--- + +**Q17:** Write a program to get the side of a equilateral triangle and print its area rounded off to 4 decimal places. +$\text{Area of equilateral triangle} = \dfrac{\sqrt{3}}{4} \times \rm{side}^2$ +>**Sample 1:** +I/p: +4
+O/p: 6.9282 + +
+>**Sample 2:** +I/p: +31 +O/p: 416.1252 + +--- + +**Q18:** Write a program to get the length and height of a right triangle and print the length of its hypotenuse rounded off to 3 decimal places using Pythagoras Theorem. +From Pythagoras theorem, $ \rm{hypotenuse} = \sqrt{\rm{base}^2 + \rm{height}^2}$ +>**Sample 1:** +I/p: +3
+4 +O/p: 5 + +
+>**Sample 2:** +I/p: +12 +6
+O/p: 13.416 + +--- + +**Q19:** Write a program to get the side of a cube and print its volume. +$\text{Volume of cube} = \rm{side}^3$ +>**Sample 1:** +I/P: 15 +O/P: 3375 + +--- + +**Q20:** Write a program to get the side of a cube and print its total surface area. +$ \text{T.S.A of Cube} = 6 \times \rm{side}^2$ +>**Sample 1:** +I/P: 15 +O/P: 1350 + +--- + +**Q21:** Write a program to get the side of a cube and print its Lateral surface area. +$\text{L.S.A of cube} = 4 \times \rm{side}^2$ + +--- + +**Q22:** Write a program to get the length, breadth and height of a cuboid and print its volume. +$\text{Volume of Cuboid} = \rm{length} \times \rm{breadth} \times \rm{height}$ +>**Sample 1:** +I/P: +43 +28 +35 +O/P: 42140 + +--- + +**Q23:** Write a program to get the length, breadth and height of a cuboid and print its Total Surface Area. +$\text{T.S.A of Cuboid} = 2 \times ( (\rm{length} \times \rm{breadth}) + (\rm{breadth} \times \rm{height}) + (\rm{height} \times \rm{length}))$ +>**Sample 1:** +I/P: +43 +28 +35 +O/P: 7378 + +--- + +**Q24:** Write a program to get the length, breadth and height of a cuboid and print its Lateral Surface Area. +$\text{L.S.A of Cuboid} = 2 \times \rm{height} \times (\rm{breadth}+ \rm{length})$ + +**** +**[Check Solution](Solution1.ipynb)** \ No newline at end of file diff --git a/.ipynb_checkpoints/Practice_code2-checkpoint.md b/.ipynb_checkpoints/Practice_code2-checkpoint.md index 6869307..1a913b7 100644 --- a/.ipynb_checkpoints/Practice_code2-checkpoint.md +++ b/.ipynb_checkpoints/Practice_code2-checkpoint.md @@ -4,68 +4,97 @@ Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) +--- + **Q1:** Write a program to get a number as input and print if it is odd or even. ->Sample1: + +>**Sample 1:** I/P: 10 O/P: Even ->Sample 2: +
+>**Sample 2:** I/P: 11 O/P: Odd +--- + **Q2:** Write a program to get a number as input and check whether it is positive, negative or zero. ->Sample1: +>**Sample 1:** I/P: 10 O/P: Positive ->Sample2: +
+>**Sample 2:** I/P: 0 O/P: Zero ->Sample3: +
+>**Sample 3:** I/P: -5 O/P: Negative +--- + **Q3:** Write a program to get the mark of a student as input print his grade. **Condition:** -mark<0 or mark>100: Invalid -90Sample1: +``` +mark < 0 or mark > 100: Invalid +90 < mark <= 100: O +80 < mark <= 90 : A+ +70 < mark <= 80 : A +60 < mark <= 70 : B+ +50 <= mark <= 60: B + 0 <= mark < 50: Fail +``` + +>**Sample 1:** I/P: 85 O/P: A+ ->Sample2: +
+>**Sample 2:** I/P: 10 O/P: Fail +--- + **Q4:** Write a program to get the age of the user and print if he is eligible to vote. + **Condition:** -A person is elgible to vote if his/her age is greater than or qual to 18 ->Sample1: +A person is eligible to vote if his/her age is greater than or equal to 18 +>**Sample 1:** I/P: 10 O/P: Ineligible ->Sample2: +
+>**Sample 2:** I/P: 27 O/P: Eligible +--- + **Q5:** Code a simple Calculator. +--- + **Q6:** Write a program to get an input from the user and print if it is a vowel or a consonant. +--- + **Q7:** Write a program to two numbers and print the greatest of them. +--- + **Q8:** Write a program to get three numbers and the print the greatest of them. +--- + **Q9:** Write a program to check if a number is a perfect square or not. +--- + **Q10:** The humidity (in percentage) and temperature (in celsius) value in a city is given as the input to the program. The program must print ***YES*** as the output if there is a possibility of rain. Else the program must print ***NO*** as the output. If one of the conditions given below is true then there is a possibility of rain. *Condition:* @@ -74,6 +103,8 @@ O/P: Eligible 3. Humidity > 70 and Temperature < 30 4. Humidity > 60 and Temperature < 24 +--- + **Q11:** Write a program to get a year as input and print if it is a leap year or not. A year is leap if it is either divisible *4* or *400* and not *100*. diff --git a/.ipynb_checkpoints/Practice_code3-checkpoint.md b/.ipynb_checkpoints/Practice_code3-checkpoint.md index 40d453e..3eec256 100644 --- a/.ipynb_checkpoints/Practice_code3-checkpoint.md +++ b/.ipynb_checkpoints/Practice_code3-checkpoint.md @@ -4,15 +4,22 @@ Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) +--- + **Q1:** Write a program to get the value of ***n*** from the user and print sum of ***n*** natural numbers as output. +--- + **Q2:** Write a program to get the values of ***n*** and ***n*** numbers from the user and print sum of the ***n*** numbers as output. -I/p: +Input: + First line contains the number ***n*** Next n lines contain ***n*** integers -O/p: -Sum of n numbers ->Sample1: + +Output: +Sum of n numbers + +>**Sample 1:** I/P: 10
1
@@ -27,32 +34,67 @@ I/P: -1
O/p: 167 +--- + **Q3:** Write a program get a number from user and print if it is prime or composite. +--- + **Q4:** Write a program to get a number from the user and print its factorial as output. +--- + **Q5:** Write a program to get the value of ***n*** from the user and print the first ***n*** terms of the Fibonacci series as output. +--- + **Q6:** Write a program to get a number ***n*** from the user and print its reverse as output. +--- + **Q7:** Write a program to get a number and check if it is an armstrong number or not. -**Condition:** A number is armstrong number if sum of cubes of its digit is equal to the number itself. ->Sample1: + +**Condition:** Armstrong / Narcissistic number is the number in any given number base, which forms the total of the same number, when each of its digits is raised to the power of the number of digits in the number. +>**Sample 1:** I/P: 153 O/P: Armstrong Number + **Explanation:** $ 1^3 + 5^3 + 3^3 = 153 $ +
+>**Sample 2:** +I/P: +407 +O/P: +Armstrong Number +**Explanation:** $ 4^3 + 0^3 + 7^3 = 407 $ + +
+>**Sample 3:** +I/P: +107 +O/P: +Not an Armstrong Number + +--- + **Q8:** Write a program to get a number ***n*** and print its multiplication table from 1 to 20. +--- + **Q9:** Write a program to get the values of ***n*** and ***n*** numbers from the user and print average of the ***n*** numbers rounded off to 4 decimal places as output. -I/p: +Input: + First line contains the number ***n*** Next n lines contain ***n*** integers -O/p: -Average of n numbers ->Sample1: + +Output: + +Average of n numbers + +>**Sample 1:** I/P: 10
1
@@ -67,10 +109,16 @@ I/P: -1
O/p: 16.7 +--- + **Q10:** Write a program to get a number ***n*** and print the ***nth*** term of Fibonacci series as output. +--- + **Q11:** Write a program to get two numbers as input and print their **HCF** as output. +--- + **Q12:** Write a program to get two numbers as input and print their **LCM** as output. **** diff --git a/.ipynb_checkpoints/Practice_code4-checkpoint.md b/.ipynb_checkpoints/Practice_code4-checkpoint.md index 620cce4..c197d22 100644 --- a/.ipynb_checkpoints/Practice_code4-checkpoint.md +++ b/.ipynb_checkpoints/Practice_code4-checkpoint.md @@ -4,16 +4,24 @@ Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) +--- + **Q1:** Write a program to define a function ***multiply*** which get two parameters and returns the product of them. +--- + + **Q2:** Write a program to create a function that gets sides of a rectangle and return its perimeter and area. -**Q3:** Write a program to create a function that gets a number ***n*** and a value and prints the value ***n*** times as output. ->Sample1: +--- + +**Q3:** Write a program to create a function that gets a number ***n*** and a value ***s*** and prints the value ***n*** times as output. +>**Sample 1:** I/P: 10
Hello -O/p: +
+O/P: Hello Hello Hello @@ -25,36 +33,71 @@ Hello Hello Hello ->Sample2: +
+>**Sample 2:** I/P: 5
1
-O/p: +
+O/P: 1
1
1
1 1 +--- + **Q4:** Write a program to define a function to determine simple interest for given values of Principal, Rate p.a. and duration in years. Simple Interest, S.I. = $\dfrac{P \times R \times T}{100}$ +--- + **Q5:** Write a program to get a number ***n*** and and print the prime numbers from 1 to ***n***. Use function to check if a number is prime or not. +--- + **Q6:** Write a program to define a function to return factorial of the number passed in it (use recursion). -**Q6:** Write a program to define a function to return factorial of the number passed in it (without recursion). +--- -**Q7:** Write a program to define a function that returns the permutation of ***n*** and ***r***.
-Permutation(n,r) = $^nP_r$ = $\dfrac{n!}{(n-r)!}$ +**Q7:** Write a program to define a function to return factorial of the number passed in it (without recursion). -**Q8:** Write a program to define a function that returns the caombinations of ***n*** and ***r***.
-Permutation(n,r) = $^nC_r$ = $\dfrac{n!}{(n-r)!~r!}$ +--- + +**Q8:** Write a program to define a function that gets a year as input and print if it is a leap year or not. -**Q9:** Write a program to define a function that gets a year as input and print if it is a leap year or not. **Condition:** A year is leap if it is either divisible *4* or *400* and not *100*. +--- + +**Q9:** Write a program to define a function that returns the permutation of ***n*** and ***r***.
+$\text{Permutation(n, r)} = {}^nP_r = \dfrac{n!}{(n-r)!}$ + +--- + +**Q10:** Write a program to define a function that returns the permutation of ***n*** and ***r***. Use recursion to compute the factorials.
+$\text{Permutation(n, r)} = {}^nP_r = \dfrac{n!}{(n-r)!}$ + +--- + +**Q11:** Write a program to define a function that returns the permutation of ***n*** and ***r***.
+$\text{Permutation(n, r)} = {}^nP_r$ = $\dfrac{n!}{(n-r)!} = n(n-1)(n-2)...r ~\text{terms}$ + +--- + +**Q12:** Write a program to define a function that returns the combination of ***n*** and ***r***.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!}$ + +--- + +**Q13:** Write a program to define a function that returns the combinations of ***n*** and ***r***. Use recursion to compute the factorials.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!}$ + +--- +**Q14:** Write a program to define a function that returns the combinations of ***n*** and ***r***.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!} = \dfrac{n(n-1)(n-2)...r ~\text{terms}}{1 \times 2 \times 3... r ~\text{(r terms)}} = \displaystyle \prod_{i ~= ~0}^{r ~-~1} \dfrac{n-i}{i+1}$ **** **[Check Solution](Solution4.ipynb)** \ No newline at end of file diff --git a/.ipynb_checkpoints/Practice_code5-checkpoint.md b/.ipynb_checkpoints/Practice_code5-checkpoint.md index fd9010e..6db1a41 100644 --- a/.ipynb_checkpoints/Practice_code5-checkpoint.md +++ b/.ipynb_checkpoints/Practice_code5-checkpoint.md @@ -4,8 +4,10 @@ Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) +--- + **Q1:** Write a program to get a number ***n*** and ***n*** numbers as input and print them as a list. ->Sample 1: +>**Sample 1:** I/p: 3
5
@@ -14,92 +16,126 @@ I/p: O/p: [5, 2, -20] +--- + **Q2:** Get the list of integers as input, sort them and print as output. ->Sample 1: +>**Sample 1:** I/P: -1 110 -10 0 20 1 60 O/P: [-10 -1 0 1 20 60 110] +--- + **Q3:** Get a list of integers as input and print the even elements present in it. (No. of even elements > 1) -> Sample 1: +>**Sample 1:** I/P: 10 20 5 -2 79 23335 40 O/p: [10 20 -2 40] +--- + **Q4:** Write a program to get a list of integers and print their product as output. (Use *reduce* method). > Sample 1: I/P: 10 20 5 41 -2 -7 23 O/P: 13202000 +--- + **Q5:** Write a program to get a list of integers and print their sum as output. (Use *sum* method). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: 90 +--- + **Q6:** Write a program to get a list of integers and print their sum as output. (use loops). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: 90 +--- + **Q7:** Write a program to get a list of integers and print their product as output. (Use loops). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: 13202000 +--- + **Q8:** Write a program to get a list of integers and print their average as output. (round off to 3 decimal places). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: 12.857 +--- + **Q9:** Write a program to get a list of integers and print the maximum value as output. (Use *max* method). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: 41 +--- + **Q10:** Write a program to get a list of integers and print the maximum value as output. (Use loops). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: 41 +--- + **Q11:** Write a program to get a list of integers and print the minimum value as output. (Use *min* method). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: -7 +--- + **Q12:** Write a program to get a list of integers and print the minimum value as output. (Use loops). -> Sample 1: +>**Sample 1:** I/P: 10 20 5 41 -2 -7 23 O/P: -7 +--- + **Q13:** Write a program to get a number ***n*** and print first ***n*** terms of Fibonacci series. +--- + **Q14:** Write a program to get a list of string values as input and print the values at even position as output. -> Sample 1: +>**Sample 1:** I/P: Hi First Second python STRING O/P: First python +--- + **Q15:** Write a program to get a list of numbers as input and print their median as output. (Median is the center-most value of the sorted list) -> Sample 1: +>**Sample 1:** I/P: 2 9 1 7 4 8 O/P: 6.5 ->Sample 2: +
+>**Sample 2:** I/P: 1 7 8 6 3 O/P: 3 +--- + **Q16:** Write a program to get a list of numbers as input and print their mode as output. (Mode is the most frequent value of the given list) -> Sample 1: +>**Sample 1:** I/P: 2 9 1 1 4 1 O/P: 1 ->Sample 2: +
+>**Sample 2:** I/P: 1 3 8 6 3 O/P: 3 +--- + **Q17:** Write a program to get the number of rows ***n*** and n rows of a matrix and print each row as a list. -> Sample1: +>**Sample 1:** I/P: 3
10 20 30 @@ -110,8 +146,10 @@ O/P: [1, 2, 3] [5, -4, -10] -**Q18:** Write a program to get the number of rows ***n*** and *nxn* matrix and print its transpose. -> Sample1: +--- + +**Q18:** Write a program to get the number of rows ***n*** and $n\times n$ matrix and print its transpose. +>**Sample1:** I/P: 3
10 20 30 @@ -122,64 +160,72 @@ O/P: 20 2 -4 30 3 -10 -**Q19:** Write a program to get number of rows ***r*** and columns ***c*** and two *rxc* matrices and print their sum as output. +--- + +**Q19:** Write a program to get number of rows ***r*** and columns ***c*** and two $r \times c$ matrices and print their sum as output. (No empty lines are provided in between the matrices) ->Sample 1: +>**Sample 1:** 4
4
9 13 5 2 1 11 7 6 3 7 4 1 -6 0 7 10

+6 0 7 10
-2 4 7 31 6 9 12 6 12 11 0 1 -9 10 2 3

+9 10 2 3
O/P: 7 17 12 33 7 20 19 12 15 18 4 2 15 10 9 13 -**Q20:** Write a program to get number of rows ***r*** and no. of columns ***c*** and three *rxc* matrices and print their sum as output. +--- + +**Q20:** Write a program to get number of rows ***r*** and no. of columns ***c*** and three $r \times c$ matrices and print their sum as output. (No empty lines are provided in between the matrices) ->Sample 1: +>**Sample 1:** 4
4
9 13 5 2 1 11 7 6 3 7 4 1 -6 0 7 10

+6 0 7 10
-2 4 7 31 6 9 12 6 12 11 0 1 -9 10 2 3

+9 10 2 3
0 2 8 6 3 7 1 0 0 0 1 2 -10 1 0 11

+10 1 0 11
O/P: 7 19 20 39 10 27 20 12 15 18 5 4 25 11 9 24 -**Q21:** Write a program to get a *mxn* matrix and a *pxq* matrix (m, n, p, q given) and print their product as output. +--- + +**Q21:** Write a program to get a $m \times n$ matrix and a $p \times q$ matrix (m, n, p, q given) and print their product as output. (No empty lines are provided in between the matrices) ->Sample1: +>**Sample1:** 3
2
-82 0 -57 -95 -91 56

+91 56
2
4
1 3 -11 24 --59 42 -15 48

+-59 42 -15 48
O/P: -82 -246 902 -1968 5548 -4161 2052 -5928 -3213 2625 -1841 4872 -**Q22:** Write a program to get a list of words and sort them in lexicograhic order. +--- + +**Q22:** Write a program to get a list of words and sort them in lexicographic order. ***** **[Check Solution](Solution5.ipynb)** \ No newline at end of file diff --git a/.ipynb_checkpoints/Practice_code6-checkpoint.md b/.ipynb_checkpoints/Practice_code6-checkpoint.md index 8a95460..971876e 100644 --- a/.ipynb_checkpoints/Practice_code6-checkpoint.md +++ b/.ipynb_checkpoints/Practice_code6-checkpoint.md @@ -19,9 +19,9 @@ Try working online at: **Q7:** Write a program to get a string and set the first letter of all the words in the string to upper case and print the modified string as output. **Q8**: Write a program to get a name from the user and print if it is a valid name as output. -**Condition:** Name is valid if contains only alphabets and there are atleast 1 uppercase and 1 lowercase characters. +**Condition:** Name is valid if contains only alphabets and there are at least 1 uppercase and 1 lowercase characters. -**Q9:** Write a program to get a variable name, replace all the whitespaces with an underscore " _ " and print the modified string as output. +**Q9:** Write a program to get a variable name, replace all the white spaces with an underscore " _ " and print the modified string as output. **Q10:** Write a program to get a string and print all the elements sorted in the alphabetical order as output. diff --git a/.ipynb_checkpoints/Practice_code7-checkpoint.md b/.ipynb_checkpoints/Practice_code7-checkpoint.md new file mode 100644 index 0000000..87ca74d --- /dev/null +++ b/.ipynb_checkpoints/Practice_code7-checkpoint.md @@ -0,0 +1,5 @@ +This Notebook Contains practice question for the note on [Tuples](DS_Tuples.ipynb). + +Try working online at: +[Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) +[Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) diff --git a/.ipynb_checkpoints/README-checkpoint.md b/.ipynb_checkpoints/README-checkpoint.md index 03edcbe..a4c5116 100644 --- a/.ipynb_checkpoints/README-checkpoint.md +++ b/.ipynb_checkpoints/README-checkpoint.md @@ -4,9 +4,29 @@ This repository contains in depth notes for Python Programming. For missing content, refer [Official Documentation](https://docs.python.org/) -For some short snippets in python, visit [30 seconds of code - python](https://www.30secondsofcode.org/python/p/1) +For some short snippets in python, visit [30 seconds of code - python](https://www.30secondsofcode.org/python/p/1) +For short notes refer, [Cheat Sheet](Cheat_sheet.pdf) + +Books: + +1. A Byte of Python by Swaroopch +[Read Online](https://python.swaroopch.com) +[Download PDF or EPUB](https://github.com/swaroopch/byte-of-python/releases/latest) +[Purchase](https://swaroopch.com/buybook) + +2. Automate the Boring Stuff with Python by Al Sweigart +[Read Online](https://automatetheboringstuff.com/2e/) +[Purchase](https://www.amazon.in/Automate-Boring-Stuff-Python-2nd/dp/1593279922/ref=sr_1_3?crid=P8EQ7A13BCC7&dchild=1&keywords=automate+the+boring+stuff+with+python&qid=1622629604&sprefix=Automate+the+boring+%2Caps%2C317&sr=8-3) + +3. Beyond the Basic Stuff with Python by Al Sweigart +[Read Online](https://inventwithpython.com/beyond/) +[Purchase](https://www.amazon.in/Python-Beyond-Basics-Al-Sweigart/dp/1593279663/ref=sr_1_3?crid=3R7C1Q4GPS9WB&dchild=1&keywords=beyond+the+basic+stuff+with+python&qid=1622629740&sprefix=Beyond+the+basic+stuff+with+%2Caps%2C322&sr=8-3) + +Read the notes using [GitHub pages](https://aniruddh-0701.github.io/Python_Programming_Notes/) ### Sequence of notes: +All the outputs are to be tested by using print statement. In the notes shared, if only names of variables/functions are given, please use print statement(s) in your code to get the output. +
  1. Installing and Using Python
  2. Introduction to Python programming
  3. @@ -16,16 +36,18 @@ For some short snippets in python, visit [30 seconds of code - python](https://w
  4. Data Structures - Lists
  5. Data Stuctures - String
  6. Data Structures - Tuples
  7. -
  8. Data Structures - Dictionaries
  9. -
  10. Data Structres - Sets
  11. -
  12. Modules and Packages
  13. +
  14. Data Structures - Dictionaries
  15. +
  16. Data Structres - Sets
  17. +
  18. Errors and Exception Handling
  19. +
  20. Modules and Packages
  21. File Handling
  22. Advanced I/O
  23. -
  24. Errors and Exception Handling
  25. Python Generators
  26. Python Iterators
  27. -
  28. Object Oriented Programming in Python
  29. -
  30. Regular Expressions
  31. +
  32. Numbers in Programming
  33. +
  34. Object Oriented Programming in Python - Part I
  35. +
  36. Object Oriented Programming in Python - Part II
  37. +
  38. Regular Expressions in Python
### Test questions: @@ -34,4 +56,4 @@ For some short snippets in python, visit [30 seconds of code - python](https://w 3. [Code Practice 3](Practice_code3.md); [Code Practice 3 Solution](Solution3.ipynb) 4. [Code Practice 4](Practice_code4.md); [Code Practice 4 Solution](Solution4.ipynb) 5. [Code Practice 5](Practice_code5.md); [Code Practice 5 Solution](Solution5.ipynb ) -6. [Code Practice 6](Practice_code6.md) \ No newline at end of file +6. [Code Practice 6](Practice_code6.md) diff --git a/.ipynb_checkpoints/factorial_recursion-checkpoint.py b/.ipynb_checkpoints/factorial_recursion-checkpoint.py new file mode 100644 index 0000000..fdcf734 --- /dev/null +++ b/.ipynb_checkpoints/factorial_recursion-checkpoint.py @@ -0,0 +1,14 @@ +# Example using factorial (n! = 1 * 2 * 3 ... n) n! = n * (n-1)! +def factorial(n, indent=''): + print(indent, n) + if -1 < n <= 1: + print(indent, 1) + return 1 # End of recursion + else: + fac = n * factorial(n-1, indent+' ') # recursive calling + print(indent, fac) + return fac + +n = int(input()) +print(factorial(n)) +# Input: 6 \ No newline at end of file diff --git a/.ipynb_checkpoints/prime_generator-checkpoint.py b/.ipynb_checkpoints/prime_generator-checkpoint.py new file mode 100644 index 0000000..4094013 --- /dev/null +++ b/.ipynb_checkpoints/prime_generator-checkpoint.py @@ -0,0 +1,27 @@ +from time import * +from itertools import * +from math import * + +def prime_gen(n): + num = 2 + while num <= n: + k = 2 + while k * k <= num: + if num % k == 0: + break + k += 1 + else: + yield num + num += 1 + +prime = 2 +prime_square = 4 +__primeval = 3 # private value + +if __name__ == '__main__': + t = time() + for i in prime_gen(10**2): + print(i) + # for i in islice(count(), 1, 10**3+1): + # print(i) + print(time()-t) diff --git a/ASCII chart.png b/ASCII_chart.png similarity index 100% rename from ASCII chart.png rename to ASCII_chart.png diff --git a/Advanced_IO.ipynb b/Advanced_IO.ipynb index 5a0c673..0a753fc 100644 --- a/Advanced_IO.ipynb +++ b/Advanced_IO.ipynb @@ -103,6 +103,66 @@ "print(d, type(d), sep = '\\n')\n", "# Input: 10 20" ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10 20 30 40 50\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 \n", + "20 \n", + "[30, 40, 50] \n" + ] + } + ], + "source": [ + "# Var length input\n", + "a, b, *c = map(int, input().split())\n", + "print(a, type(a))\n", + "print(b, type(b))\n", + "print(c, type(c))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10 20 30\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 \n", + "20 \n", + "30 \n" + ] + } + ], + "source": [ + "# one line input\n", + "x, y, z = map(int, input().split())\n", + "print(x, type(x))\n", + "print(y, type(y))\n", + "print(z, type(z))" + ] } ], "metadata": { diff --git a/Cheat_sheet.pdf b/Cheat_sheet.pdf index b429c88..6a3d669 100644 Binary files a/Cheat_sheet.pdf and b/Cheat_sheet.pdf differ diff --git a/Condition_Statements.ipynb b/Condition_Statements.ipynb index 76013ed..17194ac 100644 --- a/Condition_Statements.ipynb +++ b/Condition_Statements.ipynb @@ -4,7 +4,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Condition Statements\n", + "# Condition Statements\n", + "\n", "Condition statements or Control flow statements or Desicion Control Statements are statements that are used to control the flow or execution of a program.\n", "The flow is controlled the values of few variables that decide the proceedings of a program." ] @@ -40,8 +41,10 @@ "Executes the statements inside the block only if the condition is satisfied.\n", "\n", "Syntax: \n", - ">*if* condition: \n", - "     Statements" + "```python\n", + "if condition: \n", + " Statements\n", + "```" ] }, { @@ -74,20 +77,14 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 1, "metadata": {}, "outputs": [ - { - "name": "stdin", - "output_type": "stream", - "text": [ - " -1\n" - ] - }, { "name": "stdout", "output_type": "stream", "text": [ + "-1\n", "not zero\n" ] } @@ -108,10 +105,12 @@ "#### 2. *if - else* statements:\n", "Executes *else* when *if* condition fails \n", "Syntax: \n", - ">if condition1: \n", - "    Statements \n", + "```python\n", + "if condition1: \n", + " Statements \n", "else: \n", - "    Statements" + " Statements\n", + "```" ] }, { @@ -121,12 +120,14 @@ "#### 3. *if - elif - else* statements:\n", "Checks for truth of *elif* statement when *if* statement fails. Chain of *if-else* \n", "Syntax: \n", - ">if condition1: \n", - "    Statements\n", + "```python\n", + "if condition1: \n", + " Statements \n", "elif condition2: \n", - "    Statements\n", + " Statements \n", "else: \n", - "    Statements" + " Statements\n", + "```" ] }, { @@ -137,16 +138,18 @@ "*if else* within another *if else* statement\n", "\n", "Syntax:\n", - ">if condition1: \n", - "      if condition2: \n", - "         Statements \n", - "      else: \n", - "         Statements \n", + "```python\n", + "if condition1: \n", + " if condition2: \n", + " Statements \n", + " else: \n", + " Statements \n", "else: \n", - "      if condition3: \n", - "         Statements \n", - "      else: \n", - "         Statements " + " if condition3: \n", + " Statements \n", + " else: \n", + " Statements \n", + "```" ] }, { @@ -157,7 +160,9 @@ "One liner of *if else* statements\n", "\n", "Syntax:\n", - "> Statement1 if condition else Statement2" + "```python\n", + "Statement1 if condition else Statement2\n", + "```" ] } ], @@ -177,7 +182,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/DS_Dictionaries.ipynb b/DS_Dictionaries.ipynb new file mode 100644 index 0000000..566fa31 --- /dev/null +++ b/DS_Dictionaries.ipynb @@ -0,0 +1,1042 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Data Structures or Derived data Types in Python:\n", + "\n", + "Storing multiple values of same or different types under a single name.\n", + "They are collection of data.\n", + "\n", + "1. List\n", + "2. Tuple\n", + "3. String\n", + "4. Dictionary\n", + "5. Set \n", + "In this notebook, we'll discuss indepth on Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionary:\n", + "Dictionaries are unordered collection of data.\n", + "They are key-value mapping. \n", + "Represented by Curly braces `{}` \n", + "\n", + "```python\n", + "dictionary : {1: 10, 2: 20, 3: 30, 4: 'Hello', 5: -2.0}\n", + "```\n", + "\n", + "Defined by - key : value. \n", + "Each key-value map is separated by comma (,)\n", + "\n", + "|Keys| 1| 2| 3| 4| 5| \n", + "|---|---|---|---|---|---| \n", + "|Values| 10| 20| 30| 40| 50| " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a dictionary:\n", + "\n", + "1. '{ }'\n", + "2. dict()\n", + "\n", + "### 1. '{}'\n", + "```python\n", + "dict1 = {1:10, 2:20, 3:30}\n", + "```\n", + "### 2. dict()\n", + "Syntax: \n", + "```python\n", + "dict(iterable = None)\n", + "``` \n", + "iterable: any data structures listed above given that elements are present as key value mapping. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {}\n", + "type(d1)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{1: 10, 2: 20, 3: 35}\n" + ] + }, + { + "data": { + "text/plain": [ + "dict" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [(1, 10), (2, 20), (3, 35)]\n", + "d2 = dict(l)\n", + "print(d2)\n", + "type(d2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods or Functions in dictionaries: \n", + "There are various methods or functions that are used to work with dictionaries. \n", + "1. len \n", + "2. str \n", + "3. clear \n", + "4. copy \n", + "5. fromkeys \n", + "6. get \n", + "8. items \n", + "9. keys \n", + "10. values \n", + "11. update \n", + "12. pop\n", + "13. popitem\n", + "10. setdefault " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. len:\n", + "Returns the length of the given iterable.\n", + "\n", + "Syntax: \n", + "```python\n", + "len(iterable)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "len(d1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. str:\n", + "Returns the string format of the given dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "str(dict)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'{1: 12, 2: 23, 3: 34}'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "str(d1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. clear:\n", + "Deletes the items in the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.clear()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{}" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.clear()\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 4. copy:\n", + "Returns the shallow copy of the given dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.copy()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34}" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d2 = d1.copy()\n", + "d2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 5. fromkeys:\n", + "Returns a new dictionary form the given list of keys. By default the values are set to None.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.fromkeys(sep, val = None)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'key1': None, 'key2': None, 'key3': None}" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "key = ['key1', 'key2', 'key3']\n", + "d2 = dict.fromkeys(key)\n", + "d2" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'key1': 0, 'key2': 0, 'key3': 0}" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "key = ['key1', 'key2', 'key3']\n", + "d2 = dict.fromkeys(key, 0)\n", + "d2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6. get:\n", + "Returns the value of the given key if present else returns the default value given (None by Default).\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.get(key, default = None)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "12" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.get(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.get(4))" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.get(4, 0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 7. items:\n", + "Returns the list of key-value pairs in the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.items()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_items([(1, 12), (2, 23), (3, 34)])" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.items()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 8. keys:\n", + "Returns the list of keys present in the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.keys()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys([1, 2, 3])" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.keys()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 9. values:\n", + "Returns the list of values present on the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.values()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_values([12, 23, 34])" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.values()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 10. update:\n", + "Adds the key-value pairs in second dictionary to the first.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.update(dict)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34, 4: 45, 5: 56}" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d2 = {4: 45, 5: 56}\n", + "d1.update(d2)\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 11. pop:\n", + "Removes and returns the value of given key. If the key is absent, Error is raised if default is not given.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.pop(key, [default])\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "23\n" + ] + }, + { + "data": { + "text/plain": [ + "{1: 12, 3: 34}" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.pop(2))\n", + "d1" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "ename": "KeyError", + "evalue": "4", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0md1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m{\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m12\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m23\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m34\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0md1\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0md1\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mKeyError\u001b[0m: 4" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.pop(4))\n", + "d1" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "30\n" + ] + }, + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34}" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.pop(4, 30))\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 12. popitem:\n", + "Removes and returns the last key-value pair of the dictionary.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.popitem()\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(3, 34)\n" + ] + }, + { + "data": { + "text/plain": [ + "{1: 12, 2: 23}" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "print(d1.popitem())\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 13. setdefault:\n", + "Sets the default value to key if the key is absent.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict.setdefault(key, value)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 23, 3: 34, 4: 45}" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1.setdefault(4, 45)\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Accessing elements:\n", + "The values in the dictionary are accessed by key.\n", + "\n", + "Syntax: \n", + "```python\n", + "dictionary[key]\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "23" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1[2]" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "23" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 22: 23, 3: 34}\n", + "d1[22]" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "ename": "KeyError", + "evalue": "4", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0md1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m{\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m12\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m23\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;36m34\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0md1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mKeyError\u001b[0m: 4" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1[4]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Adding or Modifying items:\n", + "Items can be added or modified by using keys.\n", + "\n", + "If the key already exists, the value is replcaed by the new value. If not, new key-value pair is created\n", + "\n", + "Syntax: \n", + "```python\n", + "dictaionary[key] = value\n", + "``` " + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12, 2: 24, 3: 34, 4: 45}" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "d1[2] = 24 # modify\n", + "d1[4] = 45 # add\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Delete Elements:\n", + "Elements can be deleted by using the *del* keyword.\n", + "\n", + "Syntax: \n", + "```python\n", + "del dict[key]\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1: 12}" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "del d1[2], d1[3]\n", + "d1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing Items:\n", + "Use for loop to iterate through the dictionary." + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 12\n", + "2 23\n", + "3 34\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "for key, val in d1.items():\n", + " print(key, val)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sorting a dictionary:\n", + "Dictionaries are sorted only by keys." + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 12\n", + "2 23\n", + "3 34\n", + "\n", + "1 12\n", + "2 23\n", + "3 34\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 3: 34}\n", + "for i in sorted(d1.keys()):\n", + " print(i, d1[i])\n", + "print()\n", + "for i in sorted(d1):\n", + " print(i, d1[i])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested Dictionaries:\n", + "Dictionaries inside a dictionary is nested dictionary." + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 12\n", + "2 23\n", + "d {1: 12, 2: 23, 3: 34}\n" + ] + } + ], + "source": [ + "d1 = {1: 12, 2: 23, 'd': {1: 12, 2: 23, 3: 34}}\n", + "for i,j in d1.items():\n", + " print(i,j)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries and list Comprehension:\n", + "Dictionaries can be defined by comprehensions.\n", + "\n", + "Syntax: \n", + "```python\n", + "dict = {key: value (loops)}\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d2 = {x: x**2 for x in range(10)}\n", + "d2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries for switch case:\n", + "Dictionaries can be used as switch cases." + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'One'" + ] + }, + "execution_count": 55, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch = {1: 'One',\n", + " 2: 'Two', \n", + " 3: 'Three'}\n", + "switch[1]" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/DS_Lists.ipynb b/DS_Lists.ipynb index e8cc2fe..39c8397 100644 --- a/DS_Lists.ipynb +++ b/DS_Lists.ipynb @@ -24,7 +24,9 @@ "## Lists:\n", "Lists are ordered collection of data.\n", "Represented by square brackets '[ ]' \n", - "`list : [10, 20, 30, 'Hello', -2.0]`\n", + "```python\n", + "list : [10, 20, 30, 'Hello', -2.0]\n", + "```\n", "\n", "Each value in the list is called a element \n", "order of elements: index of element \n", @@ -46,9 +48,14 @@ "2. list()\n", "\n", "### 1. '[ ]'\n", + "```python\n", "l = [10, 20, 30]\n", + "```\n", "### 2. list()\n", - "Syntax: `list(iterable = None)` \n", + "Syntax: \n", + "```python\n", + "list(iterable = None)\n", + "```\n", "iterable: any data structures listed above " ] }, @@ -120,8 +127,11 @@ "metadata": {}, "source": [ "### Getting list as input:\n", + "```python\n", "list1 = list(input()) \n", - "list1 = list(input().split())" + "list1 = list(input().split())\n", + "```\n", + "To know more on `split()`, find it in [Data Structures - Strings](DS_Strings.ipynb)" ] }, { @@ -218,23 +228,23 @@ "source": [ "## Methods or Functions in list:\n", "There are various methods or functions that are used to work on lists. \n", - "1. append\n", - "2. insert\n", - "3. pop\n", - "4. map\n", - "5. filter\n", - "6. sort\n", - "7. sorted\n", - "8. extend\n", - "9. index\n", - "10. remove\n", - "11. reduce\n", - "12. reverse\n", - "13. len\n", - "14. count\n", - "15. sum\n", - "16. max\n", - "17. min\n", + "1. append \n", + "2. insert \n", + "3. pop \n", + "4. map \n", + "5. filter \n", + "6. sort \n", + "7. sorted \n", + "8. extend \n", + "9. index \n", + "10. remove \n", + "11. reduce \n", + "12. reverse \n", + "13. len \n", + "14. count \n", + "15. sum \n", + "16. max \n", + "17. min \n", "18. enumerate" ] }, @@ -244,7 +254,10 @@ "source": [ "### 1. append:\n", "Adds the given element to the end of the list. \n", - "Syntax: `list.append(element)`" + "Syntax: \n", + "```python\n", + "list.append(element)\n", + "```" ] }, { @@ -277,12 +290,15 @@ "source": [ "### 2. insert:\n", "Inserts the element at the index specified \n", - "Syntax: `list.insert(index, element)`" + "Syntax: \n", + "```python\n", + "list.insert(index, element)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -291,7 +307,7 @@ "[10, 15, 20, 25, 35, 30]" ] }, - "execution_count": 15, + "execution_count": 1, "metadata": {}, "output_type": "execute_result" } @@ -312,7 +328,10 @@ "### 3. pop:\n", "Removes and returns the element from the index specified. Default is last element\n", "\n", - "Syntax: `list.pop(index = -1)`" + "Syntax: \n", + "```python\n", + "list.pop(index = -1)\n", + "```" ] }, { @@ -355,7 +374,10 @@ "### 4. map:\n", "Applies the given function to every element in a list or iterable.\n", "\n", - "Syntax: `map(function, iterable)`" + "Syntax: \n", + "```python\n", + "map(function, iterable)\n", + "```" ] }, { @@ -435,7 +457,10 @@ "### 5. filter:\n", "Filters out the elements that match the given condition\n", "\n", - "Syntax: `filter(condition, iterable)`\n", + "Syntax: \n", + "```python\n", + "filter(condition, iterable)\n", + "```\n", "\n", "The condition should be given as a function definition which can be mapped to each variable. " ] @@ -466,7 +491,10 @@ "### 6. sort:\n", "Sorts the list as per the given condition\n", "\n", - "Syntax: `list.sort(key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "list.sort(key = None, reverse = False)\n", + "```" ] }, { @@ -507,7 +535,7 @@ ], "source": [ "l1 = ['Hi', 'Python', 'how', 'String', 'Data', 'Sorting Strings']\n", - "l1.sort()\n", + "l1.sort() #lexicographic sorting (as per unicode values)\n", "print(l1)\n", "l1.sort(key = len, reverse = True)\n", "print(l1)" @@ -520,28 +548,39 @@ "### 7. sorted:\n", "It is also function used to sort. Difference is that the sorted list should be reassigned to a variable.\n", "\n", - "Syntax: `sorted(iterable, key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "sorted(iterable, key = None, reverse = False)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 3, "metadata": {}, "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[10, 20, 50, 0, -10, -1, 100]\n" + ] + }, { "data": { "text/plain": [ "[-10, -1, 0, 10, 20, 50, 100]" ] }, - "execution_count": 17, + "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "l2 = [10, 20, 50, 0, -10, -1, 100]\n", - "l2 = sorted(l2)\n", + "l1 = [10, 20, 50, 0, -10, -1, 100]\n", + "l2 = sorted(l1)\n", + "print(l1)\n", "l2" ] }, @@ -552,7 +591,10 @@ "### 8. extend:\n", "Extends the given list using the elements of iterable, i.e. appends the elements of iterable to the given list \n", "\n", - "Syntax: `list.extend(iterable)`" + "Syntax: \n", + "```python\n", + "list.extend(iterable)\n", + "```" ] }, { @@ -606,7 +648,10 @@ "### 9. index:\n", "Returns the index of the element in the list. If multiple elements exist, it gives the index of first occurrence. If the element is not in the list, it raises an error\n", "\n", - "Syntax: `list.index(element)`" + "Syntax: \n", + "```python\n", + "list.index(element)\n", + "```" ] }, { @@ -637,7 +682,10 @@ "### 10. remove:\n", "Removes the first occurence of the element if present. Raises error when element not present\n", "\n", - "Syntax: `list.remove(value)`" + "Syntax: \n", + "```python\n", + "list.remove(value)\n", + "```" ] }, { @@ -690,7 +738,10 @@ "### 11. reduce:\n", "Sequentially applies the elements in the list to a function to give the final value. To use this we need to call *functools* module. In depth study of modules will be dealt later\n", "\n", - "Syntax: `reduce(function, list)`" + "Syntax: \n", + "```python\n", + "reduce(function, list)\n", + "```" ] }, { @@ -744,7 +795,10 @@ "### 12. reverse:\n", "Used to reverse the list.\n", "\n", - "Syntax: `list.reverse()`" + "Syntax: \n", + "```python\n", + "list.reverse()\n", + "```" ] }, { @@ -776,7 +830,10 @@ "### 13. len:\n", "Returns the length of the given iterable\n", "\n", - "Syntax: `len(iterable)`" + "Syntax: \n", + "```python\n", + "len(iterable)\n", + "```" ] }, { @@ -807,7 +864,10 @@ "### 14. count:\n", "Returns the count of the element specified\n", "\n", - "Syntax: `list.count(element)`" + "Syntax: \n", + "```python\n", + "list.count(element)\n", + "```" ] }, { @@ -846,7 +906,10 @@ "### 15. sum:\n", "returns the sum elements in the list or tuple.\n", "\n", - "Syntax: `sum(list, start = 0)`" + "Syntax: \n", + "```python\n", + "sum(list, start = 0)\n", + "```" ] }, { @@ -899,7 +962,10 @@ "### 16. max:\n", "Returns the maximum value in the list.\n", "\n", - "Syntax: `max(list, key = None)`" + "Syntax: \n", + "```python\n", + "max(list, key = None)\n", + "```" ] }, { @@ -951,7 +1017,10 @@ "### 17. min:\n", "Returns minimum value in the iterable\n", "\n", - "Syntax: `min(iterable, key = None)`" + "Syntax: \n", + "```python\n", + "min(iterable, key = None)\n", + "```" ] }, { @@ -982,7 +1051,10 @@ "### 18. enumerate:\n", "Returns the enumerate object for given list. An enumerate object is an iterable which contains ordered pair of the form `(index, value)` \n", "\n", - "Syntax: `enumerate(iterable, start = 0)`" + "Syntax: \n", + "```python\n", + "enumerate(iterable, start = 0)\n", + "```" ] }, { @@ -1024,8 +1096,8 @@ "|Negative Index| -5 | -4 | -3 | -2 | -1| \n", "\n", "Calling $i^{th}$ element: \n", - "positive index: l [i-1] \n", - "negative index: l [i - 1 - length]" + "positive index: `l[i-1]` \n", + "negative index: `l[i - 1 - length]`" ] }, { @@ -1079,9 +1151,12 @@ "metadata": {}, "source": [ "## Slicing operator:\n", - "Used to get / set a sublist of a list. Denoted by '[ ]'\n", + "Used to get / set a sublist of a list. Denoted by `'[]'`\n", "\n", - "Syntax: `list_name[start = 0 : stop = length : step = 1]`" + "Syntax: \n", + "```python\n", + "list_name[start = 0 : stop = length : step = 1]\n", + "```" ] }, { @@ -1234,8 +1309,11 @@ "It follows the form of the mathematical set-builder notation unlike the use of map and filter functions. It is used to create lists from either an existing like or a completely new list.\n", " \n", "Set bulider form:\n", - "{$x: x ~\\rm{\\epsilon~ list}$} \n", - "Example: `list1 = [expression (loops)]`" + "$\\{x: x ~\\rm{\\epsilon~ list}\\}$ \n", + "Example: \n", + "```python\n", + "list1 = [expression (loops)]\n", + "```" ] }, { @@ -1334,7 +1412,10 @@ "source": [ "## List Aliasing:\n", "Aliasing a list variable with another name. Referring a single list by multiple names. \n", - "Syntax: `new_name = old_name`" + "Syntax: \n", + "```python\n", + "new_name = old_name\n", + "```" ] }, { @@ -1384,7 +1465,10 @@ "### 1. Copy method:\n", "Creates a shallow copy of variable \n", "\n", - "Syntax: `new_list = list.copy(list_name)`" + "Syntax: \n", + "```python\n", + "new_list = list.copy(list_name)\n", + "```" ] }, { @@ -1416,7 +1500,10 @@ "### 2. slicing operator:\n", "Another method for shallow copy\n", "\n", - "Syntax: `new_list = old_list[:]`" + "Syntax: \n", + "```python\n", + "new_list = old_list[:]\n", + "```" ] }, { @@ -1448,7 +1535,10 @@ "### 3. list function:\n", "Create a new instance using list function. It also results in shallow copy\n", "\n", - "Syntax: `list_new = list(old_list)`" + "Syntax: \n", + "```python\n", + "list_new = list(old_list)\n", + "```" ] }, { @@ -1487,12 +1577,18 @@ "#### 1. copy:\n", "creates shallow copy\n", "\n", - "Syntax: `new_list = copy(list_name)`\n", + "Syntax: \n", + "```python\n", + "new_list = copy(list_name)\n", + "```\n", "\n", "#### 2. deepcopy:\n", "Creates a deep copy\n", "\n", - "Syntax: `new_list = deepcopy(list_name)`" + "Syntax: \n", + "```python\n", + "new_list = deepcopy(list_name)\n", + "```" ] }, { @@ -1535,10 +1631,16 @@ "## Multi-dimensional lists or matrices:\n", "Lists in a list is called a multidimensional list or nested lists. They are generally used to work with matrices.\n", "\n", - "Example: `list = [[10, 20, 30], [40, 50, 60]]` - Two dimensional list\n", + "Example: \n", + "```python\n", + "list = [[10, 20, 30], [40, 50, 60]] # - Two dimensional list\n", + "```\n", "\n", "### Accessing elements using index:\n", - "Syntax: `list_name[outermost list index][inner list index]...`" + "Syntax: \n", + "```python\n", + "list_name[outermost list index][inner list index]...\n", + "```" ] }, { @@ -1593,7 +1695,10 @@ "\n", "Each row of matrix is stored as a list\n", "\n", - "Example: `matrix = [[10, 20, 30], [40, 50, 60]]`\n", + "Example: \n", + "```python\n", + "matrix = [[10, 20, 30], [40, 50, 60]]\n", + "```\n", "\n", "### Matrix input:\n", "Matrix can be taken as input using loops or list comprehension." @@ -1756,7 +1861,7 @@ "A data type where elements are arranged such that the elements can only be added to and removed from the last. \n", "It follows the principle *FILO* - First In Last Out\n", "\n", - "**Methods used:** append() and pop()" + "**Methods used:** `append()` and `pop()`" ] }, { @@ -1767,7 +1872,7 @@ "A data type where elements are arranged such that the elements can only be added to the last and removed from the first. \n", "It follows the principle *FIFO* - First In First Out\n", "\n", - "**Methods Used:** append() and pop(0)" + "**Methods Used:** `append()` and `pop(0)`" ] }, { @@ -1780,11 +1885,11 @@ "### 1. Mutables:\n", "1. List\n", "2. Dictionary\n", + "4. Sets\n", "\n", "### 2. Immutable:\n", "1. Tuple\n", - "2. String\n", - "3. Sets" + "2. String" ] }, { @@ -1896,6 +2001,16 @@ "l4 = ['Namaste ', 'Hello']\n", "l4*5" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## List Comparison:\n", + "Python allows usage of relational operators on List.\n", + "\n", + "Python compares two lists using the elements present in them. Whenever a greater element is encounter thr boolean value is returned." + ] } ], "metadata": { @@ -1914,7 +2029,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/DS_Sets.ipynb b/DS_Sets.ipynb new file mode 100644 index 0000000..e8d8de6 --- /dev/null +++ b/DS_Sets.ipynb @@ -0,0 +1,977 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Data Structures or Derived data Types in Python:\n", + "\n", + "Storing multiple values of same or different types under a single name.\n", + "They are collection of data.\n", + "\n", + "1. List\n", + "2. Tuple\n", + "3. String\n", + "4. Dictionary\n", + "5. Set \n", + "In this notebook, we'll discuss indepth on Sets" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sets:\n", + "Sets are unordered collection of unique data.\n", + "Enclosed by Curly braces `{}` \n", + "\n", + "```python\n", + "set: {10, 20.2, 30.0}\n", + "```\n", + "\n", + "Each value in the set is called a element \n", + "Since set is unordered collection, it cannot be indexed. The elements are randomly stored." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a set:\n", + "\n", + "### set() method\n", + "\n", + "Syntax: \n", + "```python\n", + "set(iterable = None)\n", + "``` \n", + "iterable: any data structures listed above \n", + "\n", + "By default the `{}` map to a dictionary. So empty curly braces cannot be used." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30}" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [10, 20, 30]\n", + "s = set(l)\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30}" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s = {10, 20, 30, 10, 30}\n", + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Getting set as input:\n", + "```python\n", + "s1 = set(input()) \n", + "s2 = set(input().split())\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods or Functions in sets:\n", + "There are various methods or functions that are used to work on sets. \n", + "1. add \n", + "2. update \n", + "3. discard \n", + "4. pop \n", + "5. clear \n", + "6. len \n", + "7. issubset \n", + "8. issuperset \n", + "9. union \n", + "10. intersection \n", + "11. intersection_update \n", + "12. difference \n", + "13. symmetric_difference \n", + "14. copy \n", + "15. isdisjoint \n", + "16. max \n", + "17. min \n", + "18. enumerate\n", + "19. sum\n", + "20. sorted" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. add:\n", + "Adds an element to the end of the set.\n", + "\n", + "Syntax: `set.add(element)`" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30, 40}" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.add(40)\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. update:\n", + "Adds elements in another set to given set\n", + "\n", + "Syntax: `set.update(set)`" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 25, 30, 40}" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {10, 25, 40}\n", + "set1.update(set2)\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. discard:\n", + "Discards the given element in the set.\n", + "\n", + "Syntax: `set.discard(element)`" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 30}" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.discard(20)\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. pop:\n", + "Removes and returns a random element from set.\n", + "\n", + "Syntax: `set.pop()`" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.pop()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. clear:\n", + "Empties the set.\n", + "\n", + "Syntax: `set.clear()`" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "set()" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set1.clear()\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. len\n", + "Returns the length of the set\n", + "\n", + "Syntax: `len(set)`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. issubset:\n", + "Checks if a set subset of another.\n", + "\n", + "Syntax: `set.issubset(set)` \n", + "Or set1 <= set2" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {10, 20}\n", + "set2.issubset(set1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. issuperset:\n", + "Checks if the set superset of another.\n", + "\n", + "Syntax: `set.issuperset(set)` \n", + "Or set1 >= set2" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {10, 20, 30, 35}\n", + "set2.issuperset(set1) # set1.issubset(set2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9. union:\n", + "Returns the union of 2 sets\n", + "\n", + "Syntax: `set.union(set)` \n", + "Or set1|set2" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 12, 20, 22, 30}" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.union(set2)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 12, 20, 22, 30}" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1|set2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 10. intersection:\n", + "Returns the intersection of 2 sets\n", + "\n", + "Syntax: `set.intersection(set2)` \n", + "Or set1 & set2" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.intersection(set2)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1 & set2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 11. intersection_update:\n", + "Updates the set with intersection of given set.\n", + "\n", + "Syntax: `set.intersection_update(set)` \n", + "Or set1 &= set2" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.intersection_update(set2)\n", + "set1" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{30}" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1 &= set2\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 12. difference:\n", + "Returns the set difference of given set\n", + "\n", + "Syntax: `set1-set2` \n", + "Or set1 - set2" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20}" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.difference(set2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 13. Symmetric Difference:\n", + "Returns the symmetric difference of two sets.\n", + "\n", + "Syntax: `set.symmetric_difference(set)`\n", + "Or set1 ^ set2" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 12, 20, 22}" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {12, 22, 30}\n", + "set1.symmetric_difference(set2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 14. copy:\n", + "Copies a set\n", + "\n", + "Syntax: `set.copy()`" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{10, 20, 30}" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = set1.copy()\n", + "set2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 15. isdisjoint:\n", + "Checks if the given sets are mutually exclusive.\n", + "\n", + "Syntax: `set.isdisjoint(set)`" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "set2 = {1, 22, -37}\n", + "set1.isdisjoint(set2)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "30" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [10, -10, 20, -30, 40]\n", + "sum(l)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 16. max:\n", + "Returns the maximum value in the set.\n", + "\n", + "Syntax: `max(set, key = None)`" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "50" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 15, 50, 21, -7}\n", + "max(l)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-7" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 15, 50, 21, -7, 7}\n", + "max(l, key = lambda x: x % 5) # Maximum reminder when divided by 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 17. min:\n", + "Returns minimum value in the iterable\n", + "\n", + "Syntax: `min(iterable, key = None)`" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-7" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 15, 50, 21, -7}\n", + "min(l)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 18. enumerate:\n", + "Returns the enumerate object for given set. An enumerate object is an iterable which contains ordered pair of the form `(index, value)` \n", + "\n", + "Syntax: `enumerate(iterable, start = 0)`" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(0, 10), (1, 'Hello'), (2, 20), (3, 'a'), (4, -1)]" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = {10, 20, 'Hello', 'a', -1}\n", + "list(enumerate(l))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 19. sum:\n", + "returns the sum elements in the set.\n", + "\n", + "Syntax: `sum(set, start = 0)`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 20. sorted:\n", + "It is a function used to sort.\n", + "\n", + "Syntax: `sorted(iterable, key = None, reverse = False)`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing the elements in a set:\n", + "1. Using loops\n", + "2. Using Variable length argument ( * )\n", + "\n", + "### 1. Looping:\n", + "Use for loop to access element.\n", + "\n", + "### 2. Using * :\n", + "Using * will convert the elements of into arguements of print method" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n", + "20\n", + "30\n" + ] + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "for i in set1:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 20 30\n" + ] + } + ], + "source": [ + "set1 = {10, 20, 30}\n", + "print(*set1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Comprehensions:" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set1 = set(i+1 for i in range(0, 10))\n", + "set1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## all and any:\n", + "*any* checks if any of the element in an iterable is true.\n", + "\n", + "*all* checks if all the element on an iterable is True" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n" + ] + } + ], + "source": [ + "l = [10, 20, 30, 0]\n", + "print(any(l))\n", + "print(all(l))" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "True\n" + ] + } + ], + "source": [ + "set1 = {10, 20, 30, -1}\n", + "print(any(set1))\n", + "print(all(set1))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/DS_Strings.ipynb b/DS_Strings.ipynb index 773b4b2..12bd1b5 100644 --- a/DS_Strings.ipynb +++ b/DS_Strings.ipynb @@ -26,7 +26,9 @@ "Represented by quotes either ' ' or \" \". \n", "They are generally immutable. This means individual elements can't be changed.\n", "\n", - "`String : 'Hello', \"Python\"`\n", + "```python\n", + "Example: 'Hello', \"Python\"\n", + "```\n", "\n", "order of elements: index of element \n", "Index - may be positive or negative \n", @@ -47,9 +49,14 @@ "2. str()\n", "\n", "### 1. Quotes:\n", + "```python\n", "str = 'String'\n", + "```\n", "### 2. str()\n", - "Syntax: `str(value = None)` " + "Syntax: \n", + "```python\n", + "str(value = None)\n", + "``` " ] }, { @@ -155,7 +162,7 @@ "metadata": {}, "source": [ "### 1. Concatenation:\n", - "Two strings can be concatenated by using '+' operator." + "Two strings can be concatenated by using `+` operator." ] }, { @@ -185,7 +192,7 @@ "metadata": {}, "source": [ "### 2. Appending:\n", - "A character can be appended to string using '+=' operator or by reassignment." + "A character can be appended to string using `+=` operator or by reassignment." ] }, { @@ -216,7 +223,7 @@ "metadata": {}, "source": [ "### 3. String Multiplication:\n", - "String multiplication results a string with repitition. It can be done using ' * ' operator." + "String multiplication results a string with repitition. It can be done using `*` operator." ] }, { @@ -285,7 +292,10 @@ "### 1. capitalize:\n", "Capitalize the string. More specifically, first letter of the string in upper case and rest in lower case.\n", "\n", - "Syntax: `str.capitalize()`" + "Syntax: \n", + "```python\n", + "str.capitalize()\n", + "```" ] }, { @@ -317,7 +327,10 @@ "### 2. upper:\n", "Converts the string to upper case\n", "\n", - "Syntax: `str.upper()`" + "Syntax: \n", + "```python\n", + "str.upper()\n", + "```" ] }, { @@ -349,7 +362,10 @@ "### 3. lower:\n", "Converts the string to lowercase\n", "\n", - "Syntax: `str.lower()`" + "Syntax: \n", + "```python\n", + "str.lower()\n", + "```" ] }, { @@ -380,7 +396,10 @@ "### 4. center:\n", "Returns original string to center of given width. The empty places are filled using fillchar\n", "\n", - "Syntax: `str.center(width, fillchar)`" + "Syntax: \n", + "```python\n", + "str.center(width, fillchar)\n", + "```" ] }, { @@ -434,7 +453,10 @@ "### 5. swapcase:\n", "Swaps the case of string to lower if in uppercase, to upper in lowercase\n", "\n", - "Syntax: `str.swapcase()`" + "Syntax: \n", + "```python\n", + "str.swapcase()\n", + "```" ] }, { @@ -465,7 +487,10 @@ "### 6. find:\n", "Returns the index of start of substring if present in string else -1.\n", "\n", - "Syntax: `str.find(substring, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.find(substring, start = 0, end = length)\n", + "```" ] }, { @@ -496,7 +521,10 @@ "### 7. rfind:\n", "Returns index of start of last occurence substring if present in string else -1\n", "\n", - "Syntax: `str.rfind(substring, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.rfind(substring, start = 0, end = length)\n", + "```" ] }, { @@ -527,7 +555,10 @@ "### 8. index:\n", "Returns the index of substring given. Same as find but raises error if absent.\n", "\n", - "Syntax: `str.index(substring, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.index(substring, start = 0, end = length)\n", + "```" ] }, { @@ -558,7 +589,10 @@ "### 9. startswith:\n", "Checks if the given string starts with given Prefix.\n", "\n", - "Syntax: `str.startswith(prefix, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.startswith(prefix, start = 0, end = length)\n", + "```" ] }, { @@ -589,7 +623,10 @@ "### 10. endswith:\n", "Checks if the given string ends with the given suffix.\n", "\n", - "Syntax: `str.endswith(suffix, start = 0, end = length)`" + "Syntax: \n", + "```python\n", + "str.endswith(suffix, start = 0, end = length)\n", + "```" ] }, { @@ -620,7 +657,10 @@ "### 11. isalnum:\n", "Checks if the given string is alpha-numeric, i.e., contains only alphabets or numbers.\n", "\n", - "Syntax: `str.isalnum()`" + "Syntax: \n", + "```python\n", + "str.isalnum()\n", + "```" ] }, { @@ -672,7 +712,10 @@ "### 12. isalpha:\n", "Checks if the given string is alphabetic, i.e., contains only alphabets.\n", "\n", - "Syntax: `str.isalpha()`" + "Syntax: \n", + "```python\n", + "str.isalpha()\n", + "```" ] }, { @@ -724,7 +767,10 @@ "### 13. isdigit:\n", "Checks if the given string is numeric, i.e., contains only numbers.\n", "\n", - "Syntax: `str.isdigit()`" + "Syntax: \n", + "```python\n", + "str.isdigit()\n", + "```" ] }, { @@ -776,7 +822,10 @@ "### 14. strip:\n", "Removes the leading and trailing whitespaces by default, if any. If *chars* is given (string only), it removes only the characters in it.\n", "\n", - "Syntax: `str.strip(chars = None)`" + "Syntax: \n", + "```python\n", + "str.strip(chars = None)\n", + "```" ] }, { @@ -826,9 +875,12 @@ "metadata": {}, "source": [ "### 15. split:\n", - "Return a list of the words in the string, using *sep* as the delimiter. *maxsplit* gives the Maximum no. of splits to be done. The remaining string returned as last element. By default whitespaces, line feed and carriage returns are taken as delimiters.\n", + "Return a list of the words in the string, using `sep` as the delimiter. `maxsplit` gives the Maximum no. of splits to be done. The remaining string returned as last element. By default whitespaces, line feed and carriage returns are taken as delimiters.\n", "\n", - "Syntax: `str.split(/, sep = None, maxsplit = -1)`" + "Syntax: \n", + "```python\n", + "str.split(/, sep = None, maxsplit = -1)\n", + "```" ] }, { @@ -901,7 +953,10 @@ "### 16. join:\n", "Returns a concatenated string of iterable (containing only strings) with *char* (string) as delimiter.\n", "\n", - "Syntax: `char.join(iterable)`" + "Syntax: \n", + "```python\n", + "char.join(iterable)\n", + "```" ] }, { @@ -974,7 +1029,10 @@ "### 17. replace:\n", "Returns a copy of a string with given substring replaced by old substring. *count* is the max no. of occurences to be replaced, all be default.\n", "\n", - "Syntax: `str.replace(old_string, new_string, count = -1)`" + "Syntax: \n", + "```python\n", + "str.replace(old_string, new_string, count = -1)\n", + "```" ] }, { @@ -1005,7 +1063,10 @@ "### 18. zfill:\n", "Pads zeroes (0) to the start of the numeric string to fill the given width if width > length of string.\n", "\n", - "Syntax: `str.zfill(width)`" + "Syntax: \n", + "```python\n", + "str.zfill(width)\n", + "```" ] }, { @@ -1057,7 +1118,10 @@ "### 19. enumerate:\n", "Returns the enumeration object of given string.\n", "\n", - "Syntax: `enumerate(str)`" + "Syntax: \n", + "```python\n", + "enumerate(str)\n", + "```" ] }, { @@ -1091,7 +1155,10 @@ "### 20. len:\n", "Returns the length o given string\n", "\n", - "Syntax: `len(str)`" + "Syntax: \n", + "```python\n", + "len(str)\n", + "```" ] }, { @@ -1122,7 +1189,10 @@ "### 21. isupper:\n", "Checks if the given string is in uppercase.\n", "\n", - "Syntax: `str.isupper()`" + "Syntax: \n", + "```python\n", + "str.isupper()\n", + "```" ] }, { @@ -1153,7 +1223,10 @@ "### 22. islower:\n", "Checks if the given string is in lowercase.\n", "\n", - "Syntax: `str.islower()`" + "Syntax: \n", + "```python\n", + "str.islower()\n", + "```" ] }, { @@ -1184,7 +1257,10 @@ "### 23. lstrip:\n", "Removes the leading whitespaces by default, if any. If *chars* is given (string only), it removes only the characters in it.\n", "\n", - "Syntax: `str.lstrip(chars = None)`" + "Syntax: \n", + "```python\n", + "str.lstrip(chars = None)\n", + "```" ] }, { @@ -1215,7 +1291,10 @@ "### 24. rstrip:\n", "Removes the trailing whitespaces by default, if any. If *chars* is given (string only), it removes only the characters in it.\n", "\n", - "Syntax: `str.rstrip(chars = None)`" + "Syntax: \n", + "```python\n", + "str.rstrip(chars = None)\n", + "```" ] }, { @@ -1250,7 +1329,10 @@ "\n", "If the separator is not found, returns a 3-tuple containing the original string and two empty strings.\n", "\n", - "Syntax: `str.partition(sep)`" + "Syntax: \n", + "```python\n", + "str.partition(sep)\n", + "```" ] }, { @@ -1302,7 +1384,10 @@ "### 26. ljust:\n", "Pads given char (default - space) to the end of the string to fill the given width if width > length of string. Left justified string.\n", "\n", - "Syntax: `str.ljust(width, fillchar = ' ')`" + "Syntax: \n", + "```python\n", + "str.ljust(width, fillchar = ' ')\n", + "```" ] }, { @@ -1333,7 +1418,10 @@ "### 27. rjust:\n", "Pads given char (default - space) to the start of the string to fill the given width if width > length of string. Right justified string.\n", "\n", - "Syntax: `str.rjust(width, fillchar = ' ')`" + "Syntax: \n", + "```python\n", + "str.rjust(width, fillchar = ' ')\n", + "```" ] }, { @@ -1364,7 +1452,10 @@ "### 28. sorted:\n", "Returns sorted string as a list based on given key.\n", "\n", - "Syntax: `sorted(iterable, key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "sorted(iterable, key = None, reverse = False)\n", + "```" ] }, { @@ -1397,7 +1488,11 @@ "Elements of a string can be accessed using index.\n", "\n", "*Example:* \n", - "Consider a string, `s = 'Hello'`. Length = 5\n", + "Consider a string, \n", + "```python\n", + "s = 'Hello'\n", + "```\n", + "Length = 5\n", "\n", "| Element | 'H' | 'e' | 'l' | 'l' | 'o' | \n", "|---|---|---|---|---|---| \n", @@ -1435,9 +1530,12 @@ "metadata": {}, "source": [ "## Slicing operator:\n", - "Used to get a substring of a string. Denoted by '[ ]'\n", + "Used to get a substring of a string. Denoted by `[]`\n", "\n", - "Syntax: `string_name[start = 0 : stop = length : stride = 1]`" + "Syntax: \n", + "```python\n", + "string_name[start = 0 : stop = length : stride = 1]\n", + "```" ] }, { @@ -1470,10 +1568,10 @@ "2. Using * \n", "\n", "### 1. Looping:\n", - "Use for or while loop to access element or string.\n", + "Use *for* or *while* loop to access element or string.\n", "\n", "### 2. Using * :\n", - "Using * will convert the characters in the string into arguements of print method" + "Using `*` will convert the characters in the string into arguements of print method" ] }, { @@ -1542,12 +1640,18 @@ "### 1. ord:\n", "Returns the decimal ASCII (ordinal) value or Unicode point of given one-character string.\n", "\n", - "Syntax: `ord(c)`\n", + "Syntax: \n", + "```python\n", + "ord(c)\n", + "```\n", "\n", "### 2. chr:\n", "Returns the one character Unicode or ASCII string of given ordinal.\n", "\n", - "Syntax: `chr(i)`" + "Syntax: \n", + "```python\n", + "chr(i)\n", + "```" ] }, { @@ -1688,7 +1792,10 @@ "### 1. max:\n", "Returns the maximum value in the given string. Returns the character with maximum ASCII value in the String by default.\n", "\n", - "Syntax: `max(String, key = None)`" + "Syntax: \n", + "```python\n", + "max(String, key = None)\n", + "```" ] }, { @@ -1740,7 +1847,10 @@ "### 2. min:\n", "Returns minimum value in the string. Returns the character with minimum ASCII value in the String by default.\n", "\n", - "Syntax: `min(iterable, key = None)`" + "Syntax: \n", + "```python\n", + "min(iterable, key = None)\n", + "```" ] }, { @@ -1771,7 +1881,10 @@ "### 3. reversed:\n", "Returns iterator object of reversed string.\n", "\n", - "Syntax: `revrsed(sequence)`" + "Syntax: \n", + "```python\n", + "revrsed(sequence)\n", + "```" ] }, { @@ -1800,7 +1913,10 @@ "### 4. splitlines:\n", "Returns a list of strings split with carriage return and line feed (CRLF) as separator.\n", "\n", - "Syntax: `str.splitlines(keepends = False)`" + "Syntax: \n", + "```python\n", + "str.splitlines(keepends = False)\n", + "```" ] }, { @@ -1852,7 +1968,10 @@ "### 5. format:\n", "Returns formatted string as required.\n", "\n", - "Syntax: `str.format(*args, **kwargs)`\n", + "Syntax: \n", + "```python\n", + "str.format(*args, **kwargs)\n", + "```\n", "\n", "It was already discussed at String formatting in [Introduction to Python Programming](Introduction_to_Python_Programming.ipynb)" ] @@ -1882,7 +2001,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/DS_Tuples.ipynb b/DS_Tuples.ipynb index ba20742..7bad930 100644 --- a/DS_Tuples.ipynb +++ b/DS_Tuples.ipynb @@ -24,7 +24,9 @@ "## Tuple:\n", "Tuples are ordered collection of data. Unlike Lists they are immutable.\n", "Represented by parenthesis '( )' \n", - "`tuple : (10, 20, 30, 'Hello', -2.0)`\n", + "```python\n", + "tuple : (10, 20, 30, 'Hello', -2.0)\n", + "```\n", "\n", "Each value in the tuple is called a element \n", "order of elements: index of element \n", @@ -46,98 +48,80 @@ "2. tuple()\n", "\n", "### 1. '( )'\n", - "l = (10, 20, 30) \n", - "add a comma ',' if tuple is singleton\n", + "```python\n", + "l = (10, 20, 30)\n", + "``` \n", + "add a comma ',' if tuple is singleton,\n", + "\n", + "```python\n", + "t = (10,)\n", + "```\n", "### 2. tuple()\n", - "Syntax: `tuple(iterable = None)` \n", + "Syntax: \n", + "```python\n", + "tuple(iterable = None)\n", + "``` \n", "iterable: any data structures listed above " ] }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "(10, 30)\n" + "(10, 30)\n", + "\n" ] - }, - { - "data": { - "text/plain": [ - "tuple" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "t = (10, 30)\n", "print(t)\n", - "type(t)" + "print(type(t))" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "(10,)\n" + "(10,)\n", + "\n" ] - }, - { - "data": { - "text/plain": [ - "tuple" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "t1 = (10,)\n", "print(t1)\n", - "type(t1)" + "print(type(t1))" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "()\n" + "()\n", + "\n" ] - }, - { - "data": { - "text/plain": [ - "tuple" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "t2 = tuple()\n", "print(t2)\n", - "type(t2)" + "print(type(t2))" ] }, { @@ -156,29 +140,26 @@ "metadata": {}, "source": [ "### 1. Concatenation:\n", - "Two tuples can be concatenated by using '+' operator." + "Two tuples can be concatenated by using `+` operator." ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 4, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 30)" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] } ], "source": [ "t1 = (10, 20)\n", "t2 = (30,)\n", - "t1+t2" + "print(t1 + t2)" ] }, { @@ -186,30 +167,27 @@ "metadata": {}, "source": [ "### 2. Appending:\n", - "A tuples can be appended to string using '+=' operator or by reassignment." + "A tuples can be appended to string using `+=` operator or by reassignment." ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 5, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 30)" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] } ], "source": [ "t1 = (10, 20)\n", "t2 = (30,)\n", "t1 += t2\n", - "t1" + "print(t1)" ] }, { @@ -217,28 +195,25 @@ "metadata": {}, "source": [ "### 3. Tuple Multiplication:\n", - "Tuple multiplication results a new tuple with repitition. It can be done using ' * ' operator." + "Tuple multiplication results a new tuple with repitition. It can be done using `*` operator." ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 6, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 10, 20, 10, 20, 10, 20, 10, 20)" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 10, 20, 10, 20, 10, 20, 10, 20)\n" + ] } ], "source": [ "t1 = (10, 20)\n", - "t1*5" + "print(t1 * 5)" ] }, { @@ -270,31 +245,31 @@ "### 1. map:\n", "Applies the given function to every element in a iterable.\n", "\n", - "Syntax: `map(function, iterable)`" + "Syntax: \n", + "```python\n", + "map(function, iterable)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 10, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(3, 4, 5, 6)" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(3, 4, 5, 6)\n" + ] } ], "source": [ "def sample_fn(x):\n", - " return x+2\n", + " return x + 2\n", "t = [1, 2, 3, 4]\n", "t = tuple(map(sample_fn, t))\n", - "t" + "print(t)" ] }, { @@ -304,7 +279,10 @@ "### 2. filter:\n", "Filters out the elements that match the given condition\n", "\n", - "Syntax: `filter(condition, iterable)`\n", + "Syntax: \n", + "```python\n", + "filter(condition, iterable)\n", + "```\n", "\n", "The condition should be given as a function definition which can be mapped to each variable. " ] @@ -335,29 +313,29 @@ "### 3. sorted:\n", "Sorts the given tuple and returns a copy\n", "\n", - "Syntax: `sorted(iterable, key = None, reverse = False)`" + "Syntax: \n", + "```python\n", + "sorted(iterable, key = None, reverse = False)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 11, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(-10, -1, 0, 10, 20, 50, 100)" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(-10, -1, 0, 10, 20, 50, 100)\n" + ] } ], "source": [ "l2 = (10, 20, 50, 0, -10, -1, 100)\n", "l2 = tuple(sorted(l2))\n", - "l2" + "print(l2)" ] }, { @@ -367,28 +345,28 @@ "### 4. index:\n", "Returns the index of the element in the tuple. If multiple elements exist, it gives the index of first occurrence. If the element is not in the tuple, it raises an error\n", "\n", - "Syntax: `tuple.index(element)`" + "Syntax: \n", + "```python\n", + "tuple.index(element)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 12, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "0" - ] - }, - "execution_count": 20, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n" + ] } ], "source": [ "l = (10, 20, 30, 40, 10)\n", - "l.index(10)" + "print(l.index(10))" ] }, { @@ -398,23 +376,23 @@ "### 5. reduce:\n", "Sequentially applies the elements in the tuple to a function to give the final value. To use this we need to call *functools* module. In depth study of modules will be dealt later\n", "\n", - "Syntax: `reduce(function, tuple)`" + "Syntax: \n", + "```python\n", + "reduce(function, tuple)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 13, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "100" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "100\n" + ] } ], "source": [ @@ -425,7 +403,7 @@ "\n", "l = (10, 20, 30, 40)\n", "c = reduce(add, l)\n", - "c" + "print(c)" ] }, { @@ -452,7 +430,10 @@ "### 6. reversed:\n", "Returns iterator object of reversed tuple.\n", "\n", - "Syntax: `revrsed(sequence)`" + "Syntax: \n", + "```python\n", + "revrsed(sequence)\n", + "```" ] }, { @@ -481,28 +462,28 @@ "### 7. len:\n", "Returns the length of the given iterable\n", "\n", - "Syntax: `len(iterable)`" + "Syntax: \n", + "```python\n", + "len(iterable)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 14, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "6" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "6\n" + ] } ], "source": [ "list2 = (10, 20, 30, -1, 123, 10.0)\n", - "len(list2)" + "print(len(list2))" ] }, { @@ -512,36 +493,30 @@ "### 8. count:\n", "Returns the count of the element specified\n", "\n", - "Syntax: `tuple.count(element)`" + "Syntax: \n", + "```python\n", + "tuple.count(element)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "3\n" + "3\n", + "2\n" ] - }, - { - "data": { - "text/plain": [ - "2" - ] - }, - "execution_count": 25, - "metadata": {}, - "output_type": "execute_result" } ], "source": [ "l = (10, 20, 30, 10, 20, 25, 20, 50)\n", "print(l.count(20))\n", - "l.count(10)" + "print(l.count(10))" ] }, { @@ -551,28 +526,28 @@ "### 9. sum:\n", "Returns the sum elements in the tuple.\n", "\n", - "Syntax: `sum(tuple, start = 0)`" + "Syntax: \n", + "```python\n", + "sum(tuple, start = 0)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 16, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "30" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "30\n" + ] } ], "source": [ "l = (10, -10, 20, -30, 40)\n", - "sum(l)" + "print(sum(l))" ] }, { @@ -582,49 +557,46 @@ "### 10. max:\n", "Returns the maximum value in the tuple.\n", "\n", - "Syntax: `max(tuple, key = None)`" + "Syntax: \n", + "```python\n", + "max(tuple, key = None)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 17, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "50" - ] - }, - "execution_count": 27, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "50\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7)\n", - "max(l)" + "print(max(l))" ] }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 18, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "-7" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "-7\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7, 7)\n", - "max(l, key = lambda x: x % 5) # Maximum reminder when divided by 5" + "print(max(l, key=lambda x: x % 5)) # Maximum reminder when divided by 5" ] }, { @@ -634,49 +606,46 @@ "### 11. min:\n", "Returns minimum value in the iterable\n", "\n", - "Syntax: `min(iterable, key = None)`" + "Syntax: \n", + "```python\n", + "min(iterable, key = None)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 29, + "execution_count": 19, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "-7" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "-7\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7)\n", - "min(l)" + "print(min(l))" ] }, { "cell_type": "code", - "execution_count": 31, + "execution_count": 20, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "-7" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "-7\n" + ] } ], "source": [ "l = (10, 15, 50, 21, -7, 10.0)\n", - "min(l)" + "print(min(l))" ] }, { @@ -686,28 +655,28 @@ "### 12. enumerate:\n", "Returns the enumerate object for given tuple. An enumerate object is an iterable which contains ordered pair of the form `(index, value)` \n", "\n", - "Syntax: `enumerate(iterable, start = 0)`" + "Syntax: \n", + "```python\n", + "enumerate(iterable, start = 0)\n", + "```" ] }, { "cell_type": "code", - "execution_count": 32, + "execution_count": 21, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "((0, 10), (1, 20), (2, 'Hello'), (3, 'a'), (4, -1))" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "((0, 10), (1, 20), (2, 'Hello'), (3, 'a'), (4, -1))\n" + ] } ], "source": [ "l = (10, 20, 'Hello', 'a', -1)\n", - "tuple(enumerate(l))" + "print(tuple(enumerate(l)))" ] }, { @@ -717,7 +686,10 @@ "### 13. zip:\n", "Returns zipped object containing order pairs of elements from given iterables.\n", "\n", - "Syntax: `zip(iterables)`" + "Syntax: \n", + "```python\n", + "zip(iterables)\n", + "```" ] }, { @@ -736,7 +708,7 @@ "source": [ "l = (10, 15, 50, 21, -7, 8)\n", "t = ['Ten', 'Fifteen', 'Fifty', 'Twenty One', 'Negative Seven']\n", - "print(*zip(l,t))" + "print(*zip(l, t))" ] }, { @@ -748,7 +720,11 @@ "Elements of a tuple can be accessed using index.\n", "\n", "*Example:* \n", - "Consider a tuple, `t = (10, 20, 30, 40, 50)`. Length = 5\n", + "Consider a tuple, \n", + "```python\n", + "t = (10, 20, 30, 40, 50)\n", + "```\n", + "Length = 5\n", "\n", "| Element | 10 | 20 | 30 | 40 | 50 | \n", "|---|---|---|---|---|---| \n", @@ -766,30 +742,30 @@ "metadata": {}, "source": [ "## Slicing operator:\n", - "Used to get / set a sub-tuple of a tuple. Denoted by '[ ]'\n", + "Used to get / set a sub-tuple of a tuple. Denoted by `[]`\n", "\n", - "Syntax: `tuple_name[start = 0 : stop = length : step = 1]`" + "Syntax: \n", + "```python\n", + "tuple_name[start = 0 : stop = length : step = 1]\n", + "```" ] }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 22, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(10, 20, 30)" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] } ], "source": [ "t = (10, 20, 30, 40)\n", - "t[:3]" + "print(t[:3])" ] }, { @@ -801,10 +777,10 @@ "2. Using * \n", "\n", "### 1. Looping:\n", - "Use for or while loop to access elements.\n", + "Use *for* or *while* loop to access elements.\n", "\n", "### 2. Using * :\n", - "Using * will convert the tuple elements into individual arguments of print method" + "Using `*` will convert the tuple elements into individual arguments of print method" ] }, { @@ -854,8 +830,11 @@ "It follows the form of the mathematical set-builder notation unlike the use of map and filter functions. It is used to create tuples from either an existing one or a completely new tuple.\n", " \n", "Set bulider form:\n", - "{$x: x ~\\rm{\\epsilon~ iterable}$} \n", - "Example: `l = tuple(expression (loops))`" + "$\\{x: x ~\\rm{\\epsilon~ iterable}\\}$ \n", + "Example: \n", + "```python\n", + "t = tuple(expression (loops))\n", + "```" ] }, { @@ -888,10 +867,17 @@ "## Multi-dimensional tuples or matrices:\n", "Like Lists, tuples / lists in a tuple is called a multidimensional tuple or nested tuple. They are generally used to store matrices.\n", "\n", - "Example: `list = ((10, 20, 30), (40, 50, 60))` - Two dimensional \n", + "Example: \n", + "```python\n", + "t = ((10, 20, 30), (40, 50, 60))\n", + "# Two dimensional tuple\n", + "```\n", "\n", "### Accessing elements using index:\n", - "Syntax: `tuple_name[outermost tuple index][inner]...`" + "Syntax: \n", + "```python\n", + "tuple_name[outermost_tuple_index][inner]...[inner_most_index]\n", + "```" ] }, { @@ -903,7 +889,10 @@ "\n", "Each row of matrix is stored as a list / tuple\n", "\n", - "Example: `matrix = ([10, 20, 30], (40, 50, 60))`\n", + "Example: \n", + "```python\n", + "matrix = ([10, 20, 30], (40, 50, 60))\n", + "```\n", "\n", "### Matrix input:\n", "Matrix can be taken as input using loops or list comprehension." @@ -924,6 +913,16 @@ "## Variable length argument Tuples:\n", "The input given to variable length arguements are gathered together to form a tuple" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tuple Comparison:\n", + "Python allows usage of relational operators on Tuples.\n", + "\n", + "Python compares two tuples using the elements present in them. Whenever a greater element is encounter the boolean value is returned." + ] } ], "metadata": { @@ -942,7 +941,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/Errors_and_Exception_Handling.ipynb b/Errors_and_Exception_Handling.ipynb new file mode 100644 index 0000000..39a3da2 --- /dev/null +++ b/Errors_and_Exception_Handling.ipynb @@ -0,0 +1,679 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "199a314e-264d-40a7-9acc-cf6e1843dba7", + "metadata": {}, + "source": [ + "# Errors and Exception" + ] + }, + { + "cell_type": "markdown", + "id": "e6044ca7-f38b-492b-b869-23f5409ac9e1", + "metadata": {}, + "source": [ + "## Error:\n", + "\n", + "Errors are the problems in a program due to which the program will stop the execution.\n", + "\n", + "[Some Common Errors](https://www.thecrazyprogrammer.com/2014/08/types-of-errors-in-programming.html)\n", + "\n", + "1. Syntax Errors\n", + "2. Run-time Errors\n", + "3. Logical Errors\n", + "4. Latent Errors" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "35bf50f2-6901-4407-a684-415f7ba3f569", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ArithmeticError\n", + "AssertionError\n", + "AttributeError\n", + "BlockingIOError\n", + "BrokenPipeError\n", + "BufferError\n", + "ChildProcessError\n", + "ConnectionAbortedError\n", + "ConnectionError\n", + "ConnectionRefusedError\n", + "ConnectionResetError\n", + "EOFError\n", + "EnvironmentError\n", + "FileExistsError\n", + "FileNotFoundError\n", + "FloatingPointError\n", + "IOError\n", + "ImportError\n", + "IndentationError\n", + "IndexError\n", + "InterruptedError\n", + "IsADirectoryError\n", + "KeyError\n", + "LookupError\n", + "MemoryError\n", + "ModuleNotFoundError\n", + "NameError\n", + "NotADirectoryError\n", + "NotImplementedError\n", + "OSError\n", + "OverflowError\n", + "PermissionError\n", + "ProcessLookupError\n", + "RecursionError\n", + "ReferenceError\n", + "RuntimeError\n", + "SyntaxError\n", + "SystemError\n", + "TabError\n", + "TimeoutError\n", + "TypeError\n", + "UnboundLocalError\n", + "UnicodeDecodeError\n", + "UnicodeEncodeError\n", + "UnicodeError\n", + "UnicodeTranslateError\n", + "ValueError\n", + "WindowsError\n", + "ZeroDivisionError\n", + "ArithmeticError\n", + "AssertionError\n", + "AttributeError\n", + "BlockingIOError\n", + "BrokenPipeError\n", + "BufferError\n", + "ChildProcessError\n", + "ConnectionAbortedError\n", + "ConnectionError\n", + "ConnectionRefusedError\n", + "ConnectionResetError\n", + "EOFError\n", + "EnvironmentError\n", + "FileExistsError\n", + "FileNotFoundError\n", + "FloatingPointError\n", + "IOError\n", + "ImportError\n", + "IndentationError\n", + "IndexError\n", + "InterruptedError\n", + "IsADirectoryError\n", + "KeyError\n", + "LookupError\n", + "MemoryError\n", + "ModuleNotFoundError\n", + "NameError\n", + "NotADirectoryError\n", + "NotImplementedError\n", + "OSError\n", + "OverflowError\n", + "PermissionError\n", + "ProcessLookupError\n", + "RecursionError\n", + "ReferenceError\n", + "RuntimeError\n", + "SyntaxError\n", + "SystemError\n", + "TabError\n", + "TimeoutError\n", + "TypeError\n", + "UnboundLocalError\n", + "UnicodeDecodeError\n", + "UnicodeEncodeError\n", + "UnicodeError\n", + "UnicodeTranslateError\n", + "ValueError\n", + "WindowsError\n", + "ZeroDivisionError\n" + ] + } + ], + "source": [ + "# list of Errors and exceptions\n", + "for i in dir(__builtins__) + dir(__builtin__):\n", + " if \"Error\" in i:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "id": "de9d7e7b-70f5-444f-88b5-a1f77d213d76", + "metadata": {}, + "source": [ + "## Exception:\n", + "\n", + "Exceptions are raised when the some internal events occur which changes the normal flow of the program." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "2b604b7f-9acf-4196-9ce3-45214b38adc8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "BaseException\n", + "Exception\n", + "BaseException\n", + "Exception\n" + ] + } + ], + "source": [ + "# list of Errors and exceptions\n", + "for i in dir(__builtins__) + dir(__builtin__):\n", + " if \"Exception\" in i:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "id": "4e8439e0-145b-46a5-9f3f-4624aa99b605", + "metadata": {}, + "source": [ + "## Traceback\n", + "The script used below is present [here](Errors_and_Exception.py)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "5e69d208-e867-431e-a8b1-58669ad3a798", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "In a\n", + "In b\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[1;36m42\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 10\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36ma\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"In a\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mb\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Back in a\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36mb\u001b[1;34m()\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"In b\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[1;36m42\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 10\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "def a():\n", + " print(\"In a\")\n", + " b()\n", + " print(\"Back in a\")\n", + "\n", + "def b():\n", + " print(\"In b\")\n", + " return 42/0\n", + "\n", + "a() " + ] + }, + { + "cell_type": "markdown", + "id": "8eb6ab0f-114b-49d8-8c74-e2739fb27edf", + "metadata": {}, + "source": [ + "## Exception Handling:\n", + "\n", + "Marking the error-prone zone and controlling what happens when an error / exception is raised is Exception Handling.\n", + "\n", + "In python, Exception Handling can be done using the following:\n", + "\n", + "1. *try* block\n", + "2. *except* block\n", + "3. *else* block\n", + "4. *finally* block\n", + "\n", + "Syntax:\n", + "```python\n", + "try:\n", + " # Statements - Critical or Error Prone statements\n", + "except ErrorOrExceptionType:\n", + " # Statements - What to do to handle errors\n", + "else:\n", + " # Statements - What to do when error is not encountered\n", + "finally:\n", + " # Statements - What to do at the end of Exception Handling\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "a8ee09fb-d589-4813-b9d2-79c0b12ee419", + "metadata": {}, + "source": [ + "### 1. *try* block:\n", + "\n", + "The critical operation that might not work as indented or may malfunction is enclosed in the `try` block. If the statement(s) raise any Error, the execution proceeding in the try block is terminated and moved to `except` block\n", + "```python\n", + "try:\n", + " # Statement(s) that may cause Errors\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "02ec15b9-b1cc-4b32-93d8-edaf77014593", + "metadata": {}, + "source": [ + "### 2. *except* block\n", + "\n", + "The `except` block accepts the error/exception call and works as intended. The except block is used to filter the error that is anticipated.\n", + "```python\n", + "except ErrorOrException:\n", + "```\n", + "The proper way of defining the except block is as above. \n", + "Though leaving out the Error name part works fine, it may cause a lot of confusion in many cases and is not recommended\n", + "```python\n", + "except: # Not recommended for use\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "814e2f34-6404-48a8-8125-7f4b1e6548a9", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 123\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = input()\n", + " print(n / 10)\n", + "except TypeError:\n", + " print(\"Error occurred\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "64e4accd-13a0-4eaa-bcc4-79f693529c18", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 159\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred\n" + ] + } + ], + "source": [ + "# Example - not recommended\n", + "try:\n", + " n = input()\n", + " print(n / 10)\n", + "except: # Don't do it this way\n", + " print(\"Error occurred\")" + ] + }, + { + "cell_type": "markdown", + "id": "71a9426e-ce09-4b2e-8189-88ab2b1b0267", + "metadata": {}, + "source": [ + "### 3. *else* block\n", + "\n", + "If there is no error in the code inside `try` block, the `except` block is skipped and the `else` block is executed.\n", + "\n", + "```python\n", + "else:\n", + " # Statement(s) to run when no error is caused\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "ed6c5684-0c6a-435e-b694-b05a10caa1fc", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.0\n", + "Safe\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = int(input())\n", + " print(10 / n)\n", + "except ZeroDivisionError: # Catch when there is division by zero (0)\n", + " print(\"Error occurred\")\n", + "else:\n", + " print(\"Safe\")" + ] + }, + { + "cell_type": "markdown", + "id": "fb3ba86d-87ff-4c4e-96a8-454f73384a28", + "metadata": {}, + "source": [ + "### 4. *finally* block\n", + "This block is executed at all cases, whether or not an error is encountered inside the `try` block\n", + "```python\n", + "finally:\n", + " # Statement(s)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "4d11fabc-2543-4492-9461-ee17fecdea37", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 0\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred\n", + "End of Program\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = int(input())\n", + " print(10 / n)\n", + "except ZeroDivisionError: # Catch when there is division by zero (0)\n", + " print(\"Error occurred\")\n", + "else:\n", + " print(\"Safe\")\n", + "finally:\n", + " print(\"End of Program\")" + ] + }, + { + "cell_type": "markdown", + "id": "fdef2ae9-2552-4a7f-b0b6-151210bb1edf", + "metadata": {}, + "source": [ + "#### *as* keyword in *except*\n", + "\n", + "Almost any case of exceptions returns a message about the cause of the error. The above defined method does not get the message for use. \n", + "\n", + "Using `as` keyword, the error message can stored in a variable for use inside the `except` block.\n", + "```python\n", + "except ErrorOrException as err:\n", + " # Statement(s)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "e01e2dfd-1c55-401e-9190-446b95be8bc3", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 0\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error occurred - division by zero\n", + "End of Program\n" + ] + } + ], + "source": [ + "# Example\n", + "try:\n", + " n = int(input())\n", + " print(10 / n)\n", + "except ZeroDivisionError as e: # Catch when there is division by zero (0)\n", + " print(\"Error occurred -\", e) \n", + " # The message 'division by zero' is stored in e for use in the except block\n", + "else:\n", + " print(\"Safe\")\n", + "finally:\n", + " print(\"End of Program\")" + ] + }, + { + "cell_type": "markdown", + "id": "86e73074-5ef3-4e6c-989b-0da629ba7aa6", + "metadata": {}, + "source": [ + "## Intentionally Raising an Exception:\n", + "Python allows you to intentionally raise an exceptio at some cases using *raise* keyword.\n", + "\n", + "Syntax:\n", + "```python\n", + "raise ExceptionName(\"Message\")\n", + "```\n", + "\n", + "It is important to note that the exception following the `raise` keyword should either be an instance of a built-in exception or a class inheriting the same (Custom Exception)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "5cd07aff-ee0b-48ef-9e54-e9d2bc6bb928", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter temperature in Kelvin -1\n" + ] + }, + { + "ename": "ValueError", + "evalue": "The minimum temperature in Kelvin is absolute zero (0)", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mt\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Enter temperature in Kelvin\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mt\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"The minimum temperature in Kelvin is absolute zero (0)\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mt\u001b[0m \u001b[1;33m-\u001b[0m \u001b[1;36m273.15\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mValueError\u001b[0m: The minimum temperature in Kelvin is absolute zero (0)" + ] + } + ], + "source": [ + "# Example - Kelvin to Celsius Conversion\n", + "t = int(input(\"Enter temperature in Kelvin\"))\n", + "if t < 0:\n", + " raise ValueError(\"The minimum temperature in Kelvin is absolute zero (0)\")\n", + "else:\n", + " print(t - 273.15)" + ] + }, + { + "cell_type": "markdown", + "id": "7172133c-191e-4ae3-8fe0-7c9feb3c09e9", + "metadata": {}, + "source": [ + "## Assertion statement:\n", + "\n", + "An assertion is a sanity-check that you can turn on or turn off for testing your program.\n", + "\n", + "The easiest way to think of an assertion is to liken it to a `raise-if` statement (or to be more accurate, a raise-if-not statement). An expression or condition is tested, and if the result comes up false, an exception is raised.\n", + "\n", + "### *assert* Statement:\n", + "\n", + "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.\n", + "\n", + "```python\n", + "assert expression, \"Error message\"\n", + "```\n", + "The `assert` statement is usually enclosed by a `try` block and the exception is handled. In some cases to terminate the execution, they may not be used." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "dacfe853-1368-42ca-a88a-a0c71d25d8bc", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter temperature in Kelvin -1\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The minimum temperature in Kelvin is absolute zero (0)\n" + ] + } + ], + "source": [ + "# Example - Kelvin to Celsius Conversion\n", + "t = int(input(\"Enter temperature in Kelvin\"))\n", + "try:\n", + " assert t > 0, \"The minimum temperature in Kelvin is absolute zero (0)\"\n", + "except AssertionError as err:\n", + " print(err)\n", + "else:\n", + " print(t - 273.15)" + ] + }, + { + "cell_type": "markdown", + "id": "3181c04a-2ad4-414c-9f6d-355e3dcf9aa3", + "metadata": {}, + "source": [ + "## Creating custom Errors/Exception from built-ins:\n", + "Python has numerous built-in exceptions that force your program to output an error when something in the program goes wrong.\n", + "\n", + "However, sometimes you may need to create your own custom exceptions that serve your purpose.\n", + "\n", + "In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in `Exception` class. Most of the built-in exceptions are also derived from this class.\n", + "\n", + "```python\n", + "class My_exception(Exception):\n", + " pass\n", + "```\n", + "To know more about classes, visit [Object Oriented Programming](OOPS.ipynb)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "e31d9751-d85b-4a95-8832-f925e53e15a0", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 101\n" + ] + }, + { + "ename": "My_exception", + "evalue": "Number is large", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mMy_exception\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mn\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mn\u001b[0m \u001b[1;33m>\u001b[0m \u001b[1;36m100\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mMy_exception\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Number is large\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m \u001b[1;33m*\u001b[0m \u001b[0mn\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mMy_exception\u001b[0m: Number is large" + ] + } + ], + "source": [ + "class My_exception(Exception):\n", + " pass\n", + "\n", + "n = int(input())\n", + "if n > 100:\n", + " raise My_exception(\"Number is large\")\n", + "else:\n", + " print(2 * n)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/Errors_and_exception.py b/Errors_and_exception.py new file mode 100644 index 0000000..c1f5948 --- /dev/null +++ b/Errors_and_exception.py @@ -0,0 +1,12 @@ +def a(): + print("In a") + b() + print("Back in a") + + +def b(): + print("In b") + return 42 / 0 + + +a() diff --git a/Functions.ipynb b/Functions.ipynb index 66295e1..5cc6c20 100644 --- a/Functions.ipynb +++ b/Functions.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Functions in Python:\n", + "# Functions in Python\n", "Function is a set of organized lines of code that performs a specific, well defined task.\n", "\n", "It is used reduce the number of lines of code and improve reusability." @@ -15,20 +15,25 @@ "metadata": {}, "source": [ "Syntax: \n", - "*def* function_name(parameters): => function definition \n", - "     Statements \n", - "      *return* value(s)\n", + "```python\n", + "def function_name(parameters): # function definition \n", + " Statements\n", + " return value(s)\n", "\n", "... \n", "... \n", - "function_name(parameters) => Caller" + "function_name(parameters) # Caller\n", + "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Return statement:(*return*)\n", + "#### Return statement:\n", + "```python\n", + "return\n", + "```\n", "Returns back a value as specified. It marks the end of a function\n" ] }, @@ -42,7 +47,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -64,7 +69,7 @@ "source": [ "# Example 1:\n", "def add(a, b): # Function Definition\n", - " return a+b # returns the sum\n", + " return a + b # returns the sum\n", "x = int(input())\n", "y = int(input())\n", "print(add(x, y)) # Function Calling\n", @@ -73,20 +78,39 @@ "# 13" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Naming a function\n", + "\n", + "Like variables, python functions should also be in `lower_snake_case`\n", + "\n", + "One of the more universal, yet simple rules is: Function names should be verbs if the function changes the state of the program, and nouns if they're used to return a certain value.\n", + "\n", + "1. *Self-explanatory names*: a function `get_name()` will tell the developer what it returns as well as set_address(), is_male(), etc.\n", + "2. *Short*: a function name must be as short as possible so that it's simple to type as well as easy to remember. A function `get_number_of_pages_in_the_book()` is not good, something like `get_book_page_count()` is better.\n", + "3. Use of prefixes: use prefixes in the functions such as `get_name()`, `set_name()`, etc.\n", + "\n", + "The most important thing to note is to follow a constant naming convention throughout the function" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lambda function (Inline or Anonymous function):\n", - "One liner of a function\n", + "One liner of a function. It is created for use at one point or one statememt and is not intended to be named and stored.\n", "\n", "Syntax: \n", - "*lambda* parameters: Statement\n" + "```python\n", + "lambda parameters: Statement\n", + "```" ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -100,21 +124,33 @@ "name": "stdout", "output_type": "stream", "text": [ - "True\n" + "From is_even(x): True\n", + "From lambda: True\n" ] } ], "source": [ "# Example 1\n", - "# def c(x):\n", - "# return x % 2 == 0 #One line function to check if even\n", + "\n", + "def is_even(x):\n", + " return x % 2 == 0 # One line function to check if even\n", + "\n", "a = int(input())\n", - "c = lambda x: x % 2 == 0 # Equivalent lambda function\n", - "print(c(a))\n", + "print(\"From is_even(x):\", is_even(a))\n", + "print(\"From lambda:\", (lambda x: x % 2 == 0)(a)) # Equivalent lambda function\n", "\n", "# Input: 10" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `lambda` function is generally created for use with iterables where the function is applied to several values but at only once (that part of the code).\n", + "\n", + "The usual places include maps, filter and keys for sorting for any iterable. Visit [Lists](DS_Lists.ipynb) or [Tuples](DS_Tuples.ipynb) to know more on them" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -127,8 +163,10 @@ "\n", "A recursive function calls itself repeatedly by dividing the problem into sub problems until the solution is obtained for the smallest sub-problem.\n", "\n", - ">*def* function(paramters1): \n", - "    function(parameters2) -- Recursive calling" + "```python\n", + "def function(paramters1):\n", + " function(parameters2) # Recursive calling\n", + "```" ] }, { @@ -152,10 +190,10 @@ } ], "source": [ - "# Example using factorial\n", + "# Example using factorial (n! = 1 * 2 * 3 ... n) n! = n * (n-1)!\n", "def factorial(n):\n", " if -1\n", + "1\n", "2 * 1 \n", "3 * 2 * 1 \n", "4 * 3 * 2 * 1 \n", "5 * 4 * 3 * 2 * 1 \n", "6 * 5 * 4 * 3 * 2 * 1 \n", "\n", - "720" + "720\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can find the steps in recursion below \n", + "The '|' line indicates the same level of recursive call" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "6\n", + "|\t5\n", + "|\t|\t4\n", + "|\t|\t|\t3\n", + "|\t|\t|\t|\t2\n", + "|\t|\t|\t|\t|\t1\n", + "|\t|\t|\t|\t2\n", + "|\t|\t|\t6\n", + "|\t|\t24\n", + "|\t120\n", + "720\n" + ] + }, + { + "data": { + "text/plain": [ + "720" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# The indent paramter defines the offset of output. This program is to understand recursion only.\n", + "def fact(n, indent=''):\n", + " print(indent, n, sep='')\n", + " if 0 <= n <= 1: return 1\n", + " else:\n", + " fac = n * fact(n-1, indent + \"|\\t\")\n", + " print(indent, fac, sep='')\n", + " return fac\n", + "\n", + "fact(6)" ] }, { @@ -333,6 +427,8 @@ "def add(a, b): # Function Definition - Parameters\n", " print(a, b)\n", " return a+b # returns the sum\n", + "\n", + "\n", "x = int(input())\n", "y = int(input())\n", "print(add(b = x, a = y)) # Function Calling - Keywords are names of params used in definition\n", @@ -448,7 +544,7 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": 2, "metadata": {}, "outputs": [ { @@ -477,7 +573,7 @@ "source": [ "#Example\n", "# Example \n", - "def add(a, *b): # Function Definition - * incicates variable length arguments\n", + "def add(a, *b): # Function Definition - * indicates variable length arguments\n", " print(b)\n", " return a + sum(b) # returns the sum; sum is a built in function that returns sum of elements in an iterable\n", "x = int(input())\n", @@ -510,6 +606,31 @@ "Variable length arguments of the form key = value. Stores the values as key-value mapping or dictionary." ] }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'x': 2, 'y': 3}\n", + "x = 2\n", + "y = 3\n" + ] + } + ], + "source": [ + "#kwargs example\n", + "def kwargs_ex(**a):\n", + " print(a)\n", + " for k, v in a.items():\n", + " print(f\"{k} = {v}\")\n", + "\n", + "kwargs_ex(x=2, y=3)" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -529,7 +650,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 7, "metadata": {}, "outputs": [ { @@ -551,7 +672,10 @@ "Hello\n", "Hello\n", "Hello\n", - "10 23 10 -100\n" + "10 23 10 -100\n", + "Hello\n", + "Hello\n", + "4\n" ] }, { @@ -561,7 +685,7 @@ "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 18\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 19\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 20\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mc\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 21\u001b[0m \u001b[0mprintf\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 22\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 21\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 22\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 23\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mc\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 24\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 25\u001b[0m \u001b[1;31m# Input:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mNameError\u001b[0m: name 'c' is not defined" ] } @@ -586,9 +710,10 @@ " k = 'Hello'\n", " print(k)\n", "print(x,y,s,z)\n", - "print(c)\n", "printf()\n", "print(k)\n", + "print(i)\n", + "print(c)\n", "\n", "# Input:\n", "# 10\n", @@ -597,7 +722,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -637,7 +762,9 @@ "They act as descriptor of function, i.e., they describe the function.\n", "\n", "Calling docstings:\n", - "*function_name.__doc__*" + "```python\n", + "function_name.__doc__\n", + "```" ] }, { @@ -696,7 +823,9 @@ "source": [ "### 1. print: \n", "Syntax:\n", - "`print(values, [end=”\\n”, sep=” ”])`" + "```python\n", + "print(values, end=\"\\n\", sep\" \")\n", + "```" ] }, { @@ -810,7 +939,10 @@ "metadata": {}, "source": [ "### 2. input:\n", - "Syntax: `input(prompt=\"\")`" + "Syntax: \n", + "```python\n", + "input(prompt=\"\")\n", + "```" ] }, { @@ -834,7 +966,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -856,7 +988,10 @@ "metadata": {}, "source": [ "### 3. int:\n", - "Syntax: `int(x, base = 10)`" + "Syntax: \n", + "```python \n", + "int(x, base = 10)\n", + "```" ] }, { @@ -947,7 +1082,10 @@ "metadata": {}, "source": [ "### 4. float:\n", - "Syntax: `float(x = 0)`" + "Syntax: \n", + "```python\n", + "float(x = 0)\n", + "```" ] }, { @@ -1074,6 +1212,91 @@ "\n", "Argument given as a list/tuple is split across required variable. This is called scatter" ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " 10 23 30 40\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 (23, 30, 40)\n", + "103\n" + ] + } + ], + "source": [ + "#Example\n", + "def add(a, *b): # Function Definition \n", + " print(a, b)\n", + " return a + sum(b) # returns the sum; sum is a built in function that returns sum of elements in an iterable\n", + "\n", + "l = list(map(int, input().split()))\n", + "print(add(*l)) # Function Calling\n", + "\n", + "# Input: 10\n", + "# 23\n", + "# 30\n", + "# 40" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Higher Order Functions or Function Decorators:\n", + "\n", + "A function returning another function is called a higher order function\n", + "\n", + "```python\n", + "def function1(params):\n", + " def function2(params):\n", + " Statements\n", + "\n", + " return function2\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter a num\n", + " 6\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12\n" + ] + } + ], + "source": [ + "def deco(k): # Higher order function / decorator\n", + " def multiple(n):\n", + " return n*k\n", + " return multiple\n", + "\n", + "second_multiple = deco(2)\n", + "n = int(input(\"Enter a num\\n\"))\n", + "print(second_multiple(n))" + ] } ], "metadata": { @@ -1092,7 +1315,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/Generators.ipynb b/Generators.ipynb index 490d86c..31d9114 100644 --- a/Generators.ipynb +++ b/Generators.ipynb @@ -42,12 +42,12 @@ } ], "source": [ - "def my_first_generator():\n", + "def my_first_generator(): # Defining a generator\n", " i = 1\n", " while i<=100:\n", " yield i\n", - " i+=1\n", - "for j in my_first_generator():\n", + " i += 1\n", + "for j in my_first_generator(): # Calling a generator\n", " print(j, end=' ')" ] }, @@ -83,10 +83,116 @@ } ], "source": [ - "gen = (2*i for i in range(10))\n", + "gen = ( 2*i for i in range(10) ) # Definition of a generator\n", "for i in gen:\n", " print(i)" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## next method:\n", + "Returns the next element of the generator.\n", + "\n", + "Syntax: `generator.__next__()`" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n", + "11\n", + "12\n", + "13\n", + "14\n", + "15\n", + "16\n", + "17\n", + "18\n", + "19\n", + "20\n", + "21\n", + "22\n", + "23\n", + "24\n", + "25\n", + "26\n", + "27\n", + "28\n", + "29\n", + "30\n", + "31\n", + "32\n", + "33\n", + "34\n", + "35\n", + "36\n", + "37\n", + "38\n", + "39\n", + "40\n", + "41\n", + "42\n", + "43\n", + "44\n", + "45\n", + "46\n", + "47\n", + "48\n", + "49\n", + "50\n" + ] + } + ], + "source": [ + "def my_first_generator(): # Defining a generator\n", + " i = 1\n", + " while i<=100:\n", + " yield i\n", + " i += 1\n", + "gen = my_first_generator()\n", + "for j in range(50): # Calling a generator\n", + " print(gen.__next__())" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "2\n", + "4\n", + "6\n", + "8\n" + ] + } + ], + "source": [ + "gen = ( 2*i for i in range(10) ) # Definition of a generator\n", + "for i in range(5):\n", + " print(gen.__next__())" + ] } ], "metadata": { diff --git a/Higher_order_functions.py b/Higher_order_functions.py new file mode 100644 index 0000000..ae9c3db --- /dev/null +++ b/Higher_order_functions.py @@ -0,0 +1,8 @@ +def deco(k): # Higher order function / decorator + def multiple(n): + return n*k + return multiple + +second_multiple = deco(2) +n = int(input("Enter a num\n")) +print(second_multiple(n)) \ No newline at end of file diff --git a/Installing_and_Using_Python.md b/Installing_and_Using_Python.md index 4838a10..23a04c5 100644 --- a/Installing_and_Using_Python.md +++ b/Installing_and_Using_Python.md @@ -1,32 +1,40 @@ +--- +title: Installing and Using Python +subtitle: Installing and Using Python +--- + ## Downloading and Installing Python -The official python software (Interperter and IDLE) available at the official site: https://www.python.org -For windows 32-bit: Click on Download option in the Downloads Menu +The official python software (Interpreter and IDLE) available at [the official site](https://www.python.org) -For Windows 64-bit, MacOS and Linux/Unix, visit: https://www.python.org/downloads/ +For windows 32-bit: Click on Download option in the Downloads Menu -**** +--- -## Using Python: +## Using Python The python code can be run in Interactive Console or Script present in IDLE. -Other Integrated Development Environments like PyCharm IDE (Jet Brains), Visual Studio (MS) and Netbeans IDE may be used as needed. +Other Integrated Development Environments like PyCharm IDE (Jet Brains), Visual Studio (MS) and Net Beans IDE may be used as needed. For Interactive working for beginners, [Jupyter Notebooks](https://jupyter.org) can be used -**** +--- + +## Code Snippets and Tutorials -## Code Snippets and Tutorials: The official Python Documentation may be viewed at or [downloaded](https://docs.python.org/) -Other Private tutorials at: -1. [Tutorials Point](www.tutorialspoint.com/python/index.htm) -2. [W3Schools](www.w3schools.com/python/) -3. [Geeks for Geeks](www.geeksforgeeks.org/python-programming-language/) +Other Private tutorials at: + +1. [Tutorials Point](https://www.tutorialspoint.com/python/index.htm) +2. [W3Schools](https://www.w3schools.com/python/) +3. [Geeks for Geeks](https://www.geeksforgeeks.org/python-programming-language/) +4. [Scaler Topics](https://www.scaler.com/topics/python/what-is-python/) + +--- -**** +## Practice Code at -## Practice Code at: -1. [HackerRank](https://www.hackerrank.com/) -2. [HackerEarth](https://www.hackerearth.com/) \ No newline at end of file +1. [HackerRank](https://www.hackerrank.com/) +2. [HackerEarth](https://www.hackerearth.com/) diff --git a/Introduction_to_Python_Programming.ipynb b/Introduction_to_Python_Programming.ipynb index ecec7ac..5a23352 100644 --- a/Introduction_to_Python_Programming.ipynb +++ b/Introduction_to_Python_Programming.ipynb @@ -2,8 +2,9 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, "source": [ + "# Introduction to Python Programming\n", + "\n", "#### Program:\n", "A set of instructions to perform a specific task\n", "#### Programming Language\n", @@ -27,9 +28,9 @@ "Python versions: \n", "1.\t2.x\n", "2.\t3.x \n", - "\n", - "90% match. Small syntax and data changes. \n", - "Latest: Python 3.8.5\n", + " \n", + "Latest: Python 3.9.1\n", + "Preferred 3.8.6\n", "\n", "Things needed in a program:\n", "1.\tInput (i/p)\n", @@ -39,55 +40,67 @@ "\n", "###### Note:\n", "[value] - optional parameter" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Input:\n", "Input from the user is obtained using the input statement \n", - ">Syntax: `input(prompt = \"\")`" - ] + "Syntax: \n", + "```python\n", + "input(prompt = \"\")\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 1, - "metadata": {}, + "source": [ + "# Example 1\r\n", + "a = input('Enter a number ')\r\n", + "\r\n", + "# Example 2\r\n", + "b = input()" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Enter a number 10\n" ] } ], - "source": [ - "# Example 1\n", - "a = input('Enter a number ')\n", - "\n", - "# Example 2\n", - "b = input()" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Output:\n", - "The output is displayed to the user using the print statement\n", - "> Syntax: `print(values,..., end=”\\n”, sep=” ”)`\n" - ] + "The output is displayed to the user using the print statement \n", + "Syntax: \n", + "```python\n", + "print(values,..., end=\"\\n\", sep=\" \")\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 7, - "metadata": {}, + "source": [ + "# Example \r\n", + "print(a)\r\n", + "print()\r\n", + "print(a,b)" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "10\n", "\n", @@ -95,82 +108,76 @@ ] } ], - "source": [ - "# Example \n", - "print(a)\n", - "print()\n", - "print(a,b)" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ - "### Data in Python\n", - "\n", - "Data: Unorderd collection of information\n", - "\n", - "#### Types:\n", - "1. Numeric\n", - "2. Character\n", - "3. Boolean\n", - "4. Null\n", - "5. Derived or Complex Data Types\n", - "\n", - "#### 1. Numeric:\n", - "Associated with number \n", - "Eg: 10, 2.1, -99.7, 3.1416(pi)\n", - "\n", - "##### Types:\n", - "1. Integer (int): 10, 100, 0, -5\n", - "2. Floating point numbers or double (float): 22/7, -0.15\n", - "\n", - "#### 2. Character (char):\n", - "All characters that are defined under ASCII (American Standard Code For Information Interchange). Look the below chart for the list of characters allowed under ASCII.\n", - "\n", - "\n", - "\n", - "They are denoted using single quotes ('')\n", - "\n", - "Eg: '1', 'a', '#'\n", - "\n", - "#### 3. Boolean (bool):\n", - "Asserts if a condition is True or False\n", - "If denotion in Number: \n", - "1. True - number != 0\n", - "2. False - number = 0\n", - "\n", - "#### 4. Null or None:\n", - "If nothing is present\n", - "\n", - "Above four primitive data types\n", - "\n", - "#### 5. Complex Data Types (Derived):\n", - "Combination of above four data types\n", - "\n", - "##### Types:\n", - "1. List\n", - "2. Tuple\n", - "3. Set\n", - "4. String\n", - "5. Dictionary\n", - "\n", - "###### String:\n", - "A collection of characters\n", - "\n", - "Eg: 'Prabhu', '123', \"Hi\", \"Hello Python\" \n", - "\n", - "##### Additional types in integers (Base):\n", - "1. Binary (base 2) [0,1]\n", - "2. Octal (base 8) [0-7]\n", - "3. Decimal (base 10) [0-9] Most Common\n", - "4. HexaDecimal (base 16) [0-9, A-F] \n", + "### Data in Python\r\n", + "\r\n", + "Data: Unorderd collection of information\r\n", + "\r\n", + "#### Types:\r\n", + "1. Numeric\r\n", + "2. Character\r\n", + "3. Boolean\r\n", + "4. Null\r\n", + "5. Derived or Complex Data Types\r\n", + "\r\n", + "#### 1. Numeric:\r\n", + "Associated with number \r\n", + "Eg: 10, 2.1, -99.7, 3.1416(pi)\r\n", + "\r\n", + "##### Types:\r\n", + "1. Integer (int): 10, 100, 0, -5\r\n", + "2. Floating point numbers or double (float): 22/7, -0.15\r\n", + "\r\n", + "#### 2. Character (char):\r\n", + "All characters that are defined by Unicode. Look the below chart for the list of characters allowed under ASCII (American Standard Code for Information Interchange) which are most commonly used.\r\n", + "\r\n", + "\r\n", + "\r\n", + "They are denoted using single quotes ('')\r\n", + "\r\n", + "Eg: '1', 'a', '#'\r\n", + "\r\n", + "#### 3. Boolean (bool):\r\n", + "Asserts if a condition is True or False\r\n", + "If denotion in Number: \r\n", + "1. True - number != 0\r\n", + "2. False - number = 0\r\n", + "\r\n", + "#### 4. Null or None:\r\n", + "If nothing is present\r\n", + "\r\n", + "Above four primitive data types\r\n", + "\r\n", + "#### 5. Complex Data Types (Derived):\r\n", + "Combination of above four data types\r\n", + "\r\n", + "##### Types:\r\n", + "1. List\r\n", + "2. Tuple\r\n", + "3. Set\r\n", + "4. String\r\n", + "5. Dictionary\r\n", + "\r\n", + "###### String:\r\n", + "A collection of characters\r\n", + "\r\n", + "Eg: 'Prabhu', '123', \"Hi\", \"Hello Python\" \r\n", + "\r\n", + "##### Additional types in integers (Base):\r\n", + "1. Binary (base 2) [0,1]\r\n", + "2. Octal (base 8) [0-7]\r\n", + "3. Decimal (base 10) [0-9] Most Common\r\n", + "4. HexaDecimal (base 16) [0-9, A-F] \r\n", "The bases allowed are 2 to 35" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Literals\n", "Literals are data that are used or processed in a program.\n", @@ -187,12 +194,12 @@ "- Generally, uppercase alphabets are not used in the beginning of a variable name.\n", "\n", "##### Naming Conventions:\n", - "[Naming Convention - Wikipedia article](https://en.wikipedia.org/wiki/Naming_convention_(programming)) \n", + "Naming Convention - Wikipedia article \n", "For Easy readability \n", "- Function or use as name\n", "- first letter in lowercase\n", "- name has Multiple words:\n", - " 1. use space for underscore\n", + " 1. use underscore for space\n", " 2. joint writing with words from second in caps\n", "- No Long names\n", "\n", @@ -206,111 +213,117 @@ "\n", "E.g.: age, input_values, firstName, number, prime_num \n", "Not: user name, number_to_find_prime" - ] + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 3, - "metadata": {}, + "source": [ + "userName = input()\r\n", + "user_name = input()" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "a\n" ] } ], - "source": [ - "userName = input()\n", - "user_name = input()" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ - "### Keywords or Indentifiers or Reserved words:\n", + "### Keywords or Identifiers or Reserved words:\n", "\n", "Words used for a special purpose in program.\n", "\n", - "E.g: input, print, int, if, for, try, list, etc." - ] + "```python\n", + "Eg: input, print, int, if, for, try, list, etc.\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": null, - "metadata": {}, - "outputs": [], "source": [ - "# Key words\n", - "try\n", - "for\n", - "while\n", - "input\n", + "# Key words\r\n", + "try\r\n", + "for\r\n", + "while\r\n", + "input\r\n", "print" - ] + ], + "outputs": [], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Comments:\n", "\n", "Lines that are not executed. It used only for understanding by the programmers or users\n", "\n", "'#' is used to comment lines" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Documentation Strings or Doc strings:\n", "\n", - "''' ''' , \"\"\" \"\"\" define documentation strings.\n", + "```python\n", + "''' ''' and \"\"\" \"\"\" define documentation strings.\n", + "```\n", "\n", "Brief explanation of code.\n" - ] + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 1, - "metadata": {}, + "source": [ + "\"\"\" \r\n", + "This line gives example of docstrings.\r\n", + "This doc strings can extend many lines\r\n", + "\"\"\"\r\n", + "print('Hi')" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hi\n" ] } ], - "source": [ - "\"\"\" \n", - "This line gives example of docstrings.\n", - "This doc strings can extend many lines\n", - "\"\"\"\n", - "print('Hi')" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Type Casting and conversion:\n", "\n", "Convert one form of data into another\n", "\n", - "`type()` function gives the data type of a variable\n", + "```python\n", + "type() # function gives the data type of a variable\n", + "```\n", "\n", "|Method|Result|Syntax|\n", "|---|---|---|\n", "|int()|Converts Numeric data into integer|int(x [, base=10])|\n", "|float()|Converts Numeric Data into float|float(x)|\n", "|str()|Converts Data into string|str([x])|\n", - "|ord()|Generates decimal ASCII value of a character|ord(x)|\n", - "|chr()|Returns the ASCII character of given value|chr(x)|\n", + "|ord()|Generates Unicode code point integer value of a character|ord(x)|\n", + "|chr()|Returns the Unicode character of given value|chr(x)|\n", "|oct()|Returns octal value as a string|oct(x)|\n", "|bin()|Returns Binary value as a string|bin(x)|\n", "|hex()|Returns Hexadecimal value as a string|hex(x)|\n", @@ -318,68 +331,68 @@ "|tuple()|Returns the tuple form of given iterable|tuple([x])|\n", "|set()|Returns the set form of given iterable|set([x])|\n", "|dict()|Returns Key-value mapping|dict([x])|\n" - ] + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 10, - "metadata": {}, + "source": [ + "print(type('123.0'))\r\n", + "a = float('123.0')\r\n", + "type(a)" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "\n" ] }, { + "output_type": "execute_result", "data": { "text/plain": [ "float" ] }, - "execution_count": 10, "metadata": {}, - "output_type": "execute_result" + "execution_count": 10 } ], - "source": [ - "print(type('123.0'))\n", - "a = float('123.0')\n", - "type(a)" - ] + "metadata": {} }, { "cell_type": "code", "execution_count": 12, - "metadata": {}, + "source": [ + "print(a)\n", + "int(a)" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "123.0\n" ] }, { + "output_type": "execute_result", "data": { "text/plain": [ "123" ] }, - "execution_count": 12, "metadata": {}, - "output_type": "execute_result" + "execution_count": 12 } ], - "source": [ - "print(a)\n", - "int(a)" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Operators:\n", "Used to perform arithmetic and logical operations\n", @@ -473,11 +486,11 @@ "|---|---|---| \n", "|is|True if point to same object|a is b| \n", "|is not| True if they do not point| a is not b| \n" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "#### Expressions:\n", "\n", @@ -490,11 +503,11 @@ "Example: + 12 23\n", "3. Postfix expressions: \n", "Example: 12 23 +" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "#### Escape Sequence: \n", "Few special characters defined under ASCII for formatting strings/ output\n", @@ -514,11 +527,11 @@ "|\\u...|unicode character|\n", "|\\o...|octal values|\n", "|\\x...|hexa decimal values|" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### String formatting:\n", "String formatting or output formatting is an important part of a program output.\n", @@ -529,46 +542,48 @@ "2. Formatting using format specifiers\n", "3. Formatting using the format() method\n", "4. f-strings" - ] + ], + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "#### 1. Simple formtting\n", - "`print('string', variable)`" - ] + "```python\n", + "print('string', variable)\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 16, - "metadata": {}, + "source": [ + "name = input('Enter your name ')\n", + "print('Hello', name,', Welcome')\n", + "\n", + "# Input: Prabhu" + ], "outputs": [ { - "name": "stdin", "output_type": "stream", + "name": "stdout", "text": [ "Enter your name Prabhu\n" ] }, { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hello Prabhu , Welcome\n" ] } ], - "source": [ - "name = input('Enter your name ')\n", - "print('Hello', name,', Welcome')\n", - "\n", - "# Input: Prabhu" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "#### 2. Format Specifiers:\n", "% symbol indicate format specifiers.\n", @@ -577,207 +592,237 @@ "1. Integer: %d\n", "2. Float: %f\n", "3. Character: %c\n", - "4. String: %s \n", - "`print('string format_specifier'%(order of variables))`" - ] + "4. String: %s \n", + " \n", + "```python\n", + "print('string format_specifier'%(order of variables))\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", - "execution_count": 17, - "metadata": {}, + "execution_count": 18, + "source": [ + "name = input()\n", + "# printf(\"%d\", a); in C\n", + "print('Hello %s, Welcome'%(name))\n", + "\n", + "# Input: Sooriya" + ], "outputs": [ { - "name": "stdin", "output_type": "stream", + "name": "stdout", "text": [ " Sooriya\n" ] }, { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hello Sooriya, Welcome\n" ] } ], - "source": [ - "name = input()\n", - "# printf(\"%d\", a); in C\n", - "print('Hello %s, Welcome'%(name))\n", - "\n", - "# Input: Sooriya" - ] + "metadata": {} }, { "cell_type": "code", - "execution_count": 21, - "metadata": {}, + "execution_count": 20, + "source": [ + "str1 = 'Python'\n", + "ver = 3.8\n", + "print('Hello %s, Welcome to %s%.1f'%(name, str1, ver))\n", + "print(\"Welcome to %s%.1f %s\"%(str1, ver, name))" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hello Sooriya, Welcome to Python3.8\n", "Welcome to Python3.8 Sooriya\n" ] } ], - "source": [ - "str1 = 'Python'\n", - "ver = 3.8\n", - "print('Hello %s, Welcome to %s%.1f'%(name, str1, ver))\n", - "print(\"Welcome to %s%.1f %s\"%(str1, ver, name))" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "#### 3. Format Method:\n", "Uses `.format()` method \n", - "`print(\"string {order}\".format(variables))`" - ] + "```python \n", + "print(\"string {order}\".format(variables))\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 33, - "metadata": {}, + "source": [ + "print(\"Hello {}, Welcome\".format(name))" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hello Midhun, Welcome\n" ] } ], - "source": [ - "print(\"Hello {}, Welcome\".format(name))" - ] + "metadata": {} }, { "cell_type": "code", - "execution_count": 23, - "metadata": {}, + "execution_count": 21, + "source": [ + "string1 = 'Python'\n", + "print(\"Hello {0}, Welcome to {2}{1}\".format(name, string1, ver))\n", + "print(\"Hello {}, Welcome to {}\".format(name, string1))\n", + "print(\"Welcome to {}{} {}\".format(str1, ver, name))" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ - "Hello Sooriya, Welcome to Python3.8\n", + "Hello Sooriya, Welcome to 3.8Python\n", "Hello Sooriya, Welcome to Python\n", "Welcome to Python3.8 Sooriya\n" ] } ], - "source": [ - "string1 = 'Python'\n", - "print(\"Hello {0}, Welcome to {1}{2}\".format(name, string1, ver))\n", - "print(\"Hello {}, Welcome to {}\".format(name, string1))\n", - "print(\"Welcome to {}{} {}\".format(str1, ver, name))" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "#### 4. F-strings:\n", "F-strings or formatted strings used to format strings using variables \n", - "`f'string {variable}'` \n", + "```python \n", + "f'string {variable}'\n", + "```\n", "The f-strings came after Python 3.6" - ] + ], + "metadata": {} }, { "cell_type": "code", - "execution_count": 24, - "metadata": {}, + "execution_count": 22, + "source": [ + "print(f'Hello {name}, Welcome to {string1}')" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hello Sooriya, Welcome to Python\n" ] } ], - "source": [ - "print(f'Hello {name}, Welcome to {string1}')" - ] + "metadata": {} }, { "cell_type": "code", "execution_count": 26, - "metadata": {}, + "source": [ + "print(f'Hello {name} '\\\n", + " f'Welocme to {string1}{ver}')" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Hello Sooriya Welocme to Python3.8\n" ] } ], - "source": [ - "print(f'Hello {name} '\\\n", - " f'Welocme to {string1}{ver}')" - ] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "### Float and integer formatting:\n", "\n", "The format method is used to format integers and floats as required.\n", "\n", "#### Integer Formatting:\n", - "Leading zeroes adding to integers\n", + "Leading zeroes adding to integers \n", "Eg: 01 002\n", "##### 1. Format Specifiers:\n", - "`%d` - integer \n", - "`%0nd` - no. of leading zeroes = n - no. of digits in the integer \n", + "```python\n", + "%d - integer \n", + "%0nd - no. of leading zeroes\n", + "```\n", + "= n - no. of digits in the integer\n", "##### 2. format method:\n", - "`format(int_value, format)`\n", + "```python\n", + "format(int_value, format)\n", + "```\n", "##### 3. f-strings:\n", - "`{int_value:0nd}`\n", + "```python\n", + "{int_value:0nd}\n", + "```\n", "#### Float formatting:\n", "Round off decimal places \n", "Eg: 10.1234: 10.12\n", "##### 1. Format Specifiers:\n", - "`%f` - float \n", - "`%.2f` - 2 decimal places\n", + "```python\n", + "%f - float \n", + "%.2f - 2 decimal places\n", + "```\n", "##### 2. format method:\n", - "`format(float_value, format)`\n", + "```python\n", + "format(float_value, format)\n", + "```\n", "##### 3. f-strings:\n", - "`{float_value:.nf}`\n" - ] + "```python\n", + "f\"{float_value:.nf}\"\n", + "```\n" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "source": [], "outputs": [], - "source": [] + "metadata": {} }, { "cell_type": "markdown", - "metadata": {}, "source": [ "## Muliple Assignment in one line:\n", "Python allows assignment of different variables in one line.\n", "\n", - "Syntax: `var1, var2, var3, ... = val1, val2, val3, ...`" - ] + "Syntax: \n", + "```python \n", + "var1, var2, var3, ... = val1, val2, val3, ...\n", + "```" + ], + "metadata": {} }, { "cell_type": "code", "execution_count": 3, - "metadata": {}, + "source": [ + "a, b, c, d = 10, 20, 30, 40\n", + "print(a)\n", + "print(b)\n", + "print(d)\n", + "print(c)" + ], "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "10\n", "20\n", @@ -786,13 +831,7 @@ ] } ], - "source": [ - "a, b, c, d = 10, 20, 30, 40\n", - "print(a)\n", - "print(b)\n", - "print(d)\n", - "print(c)" - ] + "metadata": {} } ], "metadata": { @@ -811,9 +850,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 4 -} +} \ No newline at end of file diff --git a/Looping_Statements.ipynb b/Looping_Statements.ipynb index 7ee587d..1dbd613 100644 --- a/Looping_Statements.ipynb +++ b/Looping_Statements.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Looping Statements:\n", + "# Looping Statements\n", "Execute a group of lines repeatedly.\n", "\n", "Finite looping is the best practice in programming but infinite looping are done because they are easy at times.\n", @@ -25,8 +25,10 @@ "For loop is used to iterate through a sequence or iterator.\n", "Lists, tuple, dictionary and string.\n", "Syntax:\n", - ">*for* value *in* iterable: \n", - "    Statements" + "```python\n", + "for value in iterable: \n", + " Statements\n", + "```" ] }, { @@ -108,8 +110,11 @@ "#### Range function:\n", "Used to create an sequence/object from *start* to *stop* in *steps*\n", "\n", - "Syntax: *range*(stop) \n", - "*range*(start, stop, [step=1])" + "Syntax: \n", + "```python\n", + "range(stop) \n", + "range(start, stop, [step=1])\n", + "```" ] }, { @@ -226,8 +231,10 @@ "Preferred for variable conditions\n", "\n", "Syntax: \n", - ">*while* condition: \n", - "   Statements" + "```python\n", + "while condition: \n", + " Statements\n", + "```" ] }, { @@ -485,7 +492,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 2, "metadata": {}, "outputs": [ { @@ -567,7 +574,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/Modules_and_Packages.ipynb b/Modules_and_Packages.ipynb new file mode 100644 index 0000000..0766d66 --- /dev/null +++ b/Modules_and_Packages.ipynb @@ -0,0 +1,1336 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Modules and Packages\n", + "Modules are files that contain functions, variables or classes that can be used without redefining them. They're generally written in Python.\n", + "\n", + "Packages are directory or folders which conatin a number of modules or packages in them." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Few built-in Modules are:\n", + "1. \\_\\_builtins\\_\\_\n", + "0. \\_\\_file\\_\\_\n", + "2. math\n", + "3. cmath\n", + "2. sys\n", + "4. os\n", + "5. itertools\n", + "6. string" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The basics of working with module are discussed using a file *prime_generator.py*\n", + "\n", + "Code: \n", + "```python\n", + "from time import *\n", + "from itertools import *\n", + "from math import *\n", + "\n", + "def prime_gen(n):\n", + " num = 2\n", + " while num <= n:\n", + " k = 2\n", + " while k * k <= num:\n", + " if num % k == 0:\n", + " break\n", + " k += 1\n", + " else:\n", + " yield num\n", + " num += 1\n", + "\n", + "prime = 2\n", + "prime_square = 4\n", + "__primeval = 3\n", + "\n", + "if __name__ == '__main__':\n", + " t = time()\n", + " for i in prime_gen(10 ** 2):\n", + " print(i)\n", + " print(time()-t)\n", + "```\n", + "\n", + "Contents:\n", + "1. prime_gen - function or generator \n", + "2. prime - varaiable (constant when imported)\n", + "3. prime_square - variable (constant when imported)\n", + "4. \\_\\_primeval - private value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## import statement:\n", + "The *import* keyword is used to import a module or package.\n", + "\n", + "Syntax: \n", + "```python\n", + "import module_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "import prime_generator\n", + "\n", + "for i in prime_generator.prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## from statement:\n", + "The *from* keyword is used to import a specific set of functions or classes from a module.\n", + "\n", + "Syntax: \n", + "```python\n", + "from module_name import function_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "from prime_generator import prime_gen\n", + "\n", + "for i in prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Importing all the objects from the module:\n", + "To import all the functions or objects, use * .\n", + "\n", + "Syntax: \n", + "```python\n", + "from module_name import *\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "from prime_generator import *\n", + "\n", + "for i in prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## **as** Keyword:\n", + "*as* Keyword is used to have a custom name for imported module or function.\n", + "\n", + "Syntax: \n", + "\n", + "```python\n", + "import moule_name as custom_name\n", + "from module_name import function_name as custom_name\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "import prime_generator as pg\n", + "\n", + "for i in pg.prime_gen(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 3 5 7 11 13 17 19 " + ] + } + ], + "source": [ + "from prime_generator import prime_gen as pgf\n", + "\n", + "for i in pgf(20):\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## \\_\\_name\\_\\_:\n", + "It returns the name of the module without the extension. If called for main executing program (main module), it returns '\\_\\_main\\_\\_'\n", + "\n", + "Syntax: \n", + "```python\n", + "module_name.__name__\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "prime_generator\n", + "__main__\n" + ] + } + ], + "source": [ + "import prime_generator as pg\n", + "\n", + "print(pg.__name__)\n", + "print(__name__)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## dir method:\n", + "\n", + "Returns the list of attributes (that are relevant) of an object or a module. By default, it gives the details of main module.\n", + "\n", + "Syntax: \n", + "```python\n", + "dir([object])\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__primeval', '__spec__', 'accumulate', 'acos', 'acosh', 'altzone', 'asctime', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'chain', 'comb', 'combinations', 'combinations_with_replacement', 'compress', 'copysign', 'cos', 'cosh', 'count', 'ctime', 'cycle', 'daylight', 'degrees', 'dist', 'dropwhile', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'filterfalse', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'get_clock_info', 'gmtime', 'groupby', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'islice', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'localtime', 'log', 'log10', 'log1p', 'log2', 'mktime', 'modf', 'monotonic', 'monotonic_ns', 'nan', 'nextafter', 'perf_counter', 'perf_counter_ns', 'perm', 'permutations', 'pi', 'pow', 'prime', 'prime_gen', 'prime_square', 'process_time', 'process_time_ns', 'prod', 'product', 'radians', 'remainder', 'repeat', 'sin', 'sinh', 'sleep', 'sqrt', 'starmap', 'strftime', 'strptime', 'struct_time', 'takewhile', 'tan', 'tanh', 'tau', 'tee', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'trunc', 'tzname', 'ulp', 'zip_longest']\n", + "\n", + "['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']\n", + "\n", + "['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'prime_generator', 'quit']\n" + ] + } + ], + "source": [ + "import prime_generator\n", + "\n", + "print(dir(prime_generator))\n", + "print()\n", + "print(dir(prime_generator.prime_gen))\n", + "print()\n", + "print(dir())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## namespace:\n", + "\n", + "A container that has a list of names (objects) defined in a module. It is the place where python searches for objects defined and used in a function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Global, Local and Built-in Namespaces\n", + "\n", + "### Global:\n", + "Namespace containing values defined throughout a file or module (globally)\n", + "\n", + "### Local:\n", + "Namespace containing values defined in a part of a file or module (Locally)\n", + "\n", + "### Builtin:\n", + "Namespace containing values common for all python file.\n", + "\n", + "## Order of Search:\n", + "1. Local\n", + "2. Global\n", + "3. Builtin" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Packages:\n", + "Directory or folder containing a number of modules and subpackages.\n", + "\n", + "It contains '\\_\\_init\\_\\_.py' file which defines the modules that can be imported from the package.\n", + "\n", + "### Importing a module from package: \n", + "```python\n", + "import package_name.module_name\n", + "import package_name.module_name as custom_name\n", + "```\n", + "\n", + "### Import a specific object from a module:\n", + "```python\n", + "from package_name.module_name import object_name\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Builtins:\n", + "\n", + "\\_\\_builtins\\_\\_ module contains the list of methods and variables that are standard definitions in Python." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ArithmeticError\n", + "AssertionError\n", + "AttributeError\n", + "BaseException\n", + "BlockingIOError\n", + "BrokenPipeError\n", + "BufferError\n", + "BytesWarning\n", + "ChildProcessError\n", + "ConnectionAbortedError\n", + "ConnectionError\n", + "ConnectionRefusedError\n", + "ConnectionResetError\n", + "DeprecationWarning\n", + "EOFError\n", + "Ellipsis\n", + "EnvironmentError\n", + "Exception\n", + "False\n", + "FileExistsError\n", + "FileNotFoundError\n", + "FloatingPointError\n", + "FutureWarning\n", + "GeneratorExit\n", + "IOError\n", + "ImportError\n", + "ImportWarning\n", + "IndentationError\n", + "IndexError\n", + "InterruptedError\n", + "IsADirectoryError\n", + "KeyError\n", + "KeyboardInterrupt\n", + "LookupError\n", + "MemoryError\n", + "ModuleNotFoundError\n", + "NameError\n", + "None\n", + "NotADirectoryError\n", + "NotImplemented\n", + "NotImplementedError\n", + "OSError\n", + "OverflowError\n", + "PendingDeprecationWarning\n", + "PermissionError\n", + "ProcessLookupError\n", + "RecursionError\n", + "ReferenceError\n", + "ResourceWarning\n", + "RuntimeError\n", + "RuntimeWarning\n", + "StopAsyncIteration\n", + "StopIteration\n", + "SyntaxError\n", + "SyntaxWarning\n", + "SystemError\n", + "SystemExit\n", + "TabError\n", + "TimeoutError\n", + "True\n", + "TypeError\n", + "UnboundLocalError\n", + "UnicodeDecodeError\n", + "UnicodeEncodeError\n", + "UnicodeError\n", + "UnicodeTranslateError\n", + "UnicodeWarning\n", + "UserWarning\n", + "ValueError\n", + "Warning\n", + "WindowsError\n", + "ZeroDivisionError\n", + "__IPYTHON__\n", + "__build_class__\n", + "__debug__\n", + "__doc__\n", + "__import__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "abs\n", + "all\n", + "any\n", + "ascii\n", + "bin\n", + "bool\n", + "breakpoint\n", + "bytearray\n", + "bytes\n", + "callable\n", + "chr\n", + "classmethod\n", + "compile\n", + "complex\n", + "copyright\n", + "credits\n", + "delattr\n", + "dict\n", + "dir\n", + "display\n", + "divmod\n", + "enumerate\n", + "eval\n", + "exec\n", + "filter\n", + "float\n", + "format\n", + "frozenset\n", + "get_ipython\n", + "getattr\n", + "globals\n", + "hasattr\n", + "hash\n", + "help\n", + "hex\n", + "id\n", + "input\n", + "int\n", + "isinstance\n", + "issubclass\n", + "iter\n", + "len\n", + "license\n", + "list\n", + "locals\n", + "map\n", + "max\n", + "memoryview\n", + "min\n", + "next\n", + "object\n", + "oct\n", + "open\n", + "ord\n", + "pow\n", + "print\n", + "property\n", + "range\n", + "repr\n", + "reversed\n", + "round\n", + "set\n", + "setattr\n", + "slice\n", + "sorted\n", + "staticmethod\n", + "str\n", + "sum\n", + "super\n", + "tuple\n", + "type\n", + "vars\n", + "zip\n" + ] + } + ], + "source": [ + "builtin = dir(__builtins__)\n", + "for i in builtin:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## \\_\\_file\\_\\_ module:\n", + "\n", + "It contains the list of builtin variables and functions that can be used in the current file." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### contents:\n", + "\\_\\_add\\_\\_ \n", + "\\_\\_class\\_\\_ \n", + "\\_\\_contains\\_\\_ \n", + "\\_\\_delattr\\_\\_ \n", + "\\_\\_dir\\_\\_ \n", + "\\_\\_doc\\_\\_ \n", + "\\_\\_eq\\_\\_ \n", + "\\_\\_format\\_\\_ \n", + "\\_\\_ge\\_\\_ \n", + "\\_\\_getattribute\\_\\_ \n", + "\\_\\_getitem\\_\\_ \n", + "\\_\\_getnewargs\\_\\_ \n", + "\\_\\_gt\\_\\_ \n", + "\\_\\_hash\\_\\_ \n", + "\\_\\_init\\_\\_ \n", + "\\_\\_init_subclass\\_\\_ \n", + "\\_\\_iter\\_\\_ \n", + "\\_\\_le\\_\\_ \n", + "\\_\\_len\\_\\_ \n", + "\\_\\_lt\\_\\_ \n", + "\\_\\_mod\\_\\_ \n", + "\\_\\_mul\\_\\_ \n", + "\\_\\_ne\\_\\_ \n", + "\\_\\_new\\_\\_ \n", + "\\_\\_reduce\\_\\_ \n", + "\\_\\_reduce_ex\\_\\_ \n", + "\\_\\_repr\\_\\_ \n", + "\\_\\_rmod\\_\\_ \n", + "\\_\\_rmul\\_\\_ \n", + "\\_\\_setattr\\_\\_ \n", + "\\_\\_sizeof\\_\\_ \n", + "\\_\\_str\\_\\_ \n", + "\\_\\_subclasshook\\_\\_ \n", + "capitalize \n", + "casefold \n", + "center \n", + "count \n", + "encode \n", + "endswith \n", + "expandtabs \n", + "find \n", + "format \n", + "format_map \n", + "index \n", + "isalnum \n", + "isalpha \n", + "isascii \n", + "isdecimal \n", + "isdigit \n", + "isidentifier \n", + "islower \n", + "isnumeric \n", + "isprintable \n", + "isspace \n", + "istitle \n", + "isupper \n", + "join \n", + "ljust \n", + "lower \n", + "lstrip \n", + "maketrans \n", + "partition \n", + "replace \n", + "rfind \n", + "rindex \n", + "rjust \n", + "rpartition \n", + "rsplit \n", + "rstrip \n", + "split \n", + "splitlines \n", + "startswith \n", + "strip \n", + "swapcase \n", + "title \n", + "translate \n", + "upper \n", + "zfill " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Private in modules:\n", + "\n", + "Objects can be restricted to usage when running as a main module. They cannot be imported when importing the complete module using ' * '.\n", + "\n", + "They start and end with double underscores, \\_\\_" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n" + ] + } + ], + "source": [ + "import prime_generator as pg\n", + "\n", + "print(pg.__primeval)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name '__primeval' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mprime_generator\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[1;33m*\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0m__primeval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mNameError\u001b[0m: name '__primeval' is not defined" + ] + } + ], + "source": [ + "from prime_generator import *\n", + "\n", + "print(__primeval)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## globals(), locals() and reload()\n", + "\n", + "globals - returns the list of objects that can be accessed globally from that point.\n", + "\n", + "locals - returns the list of objects that can be accessed locally from that point.\n", + "\n", + "reload - reloads the given module. (imported from impotlib module)\n", + "\n", + "Syntax: \n", + "```python\n", + "reload(module_name)\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## math:\n", + "This module contains list of all mathematical functions." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__doc__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "acos\n", + "acosh\n", + "asin\n", + "asinh\n", + "atan\n", + "atan2\n", + "atanh\n", + "ceil\n", + "comb\n", + "copysign\n", + "cos\n", + "cosh\n", + "degrees\n", + "dist\n", + "e\n", + "erf\n", + "erfc\n", + "exp\n", + "expm1\n", + "fabs\n", + "factorial\n", + "floor\n", + "fmod\n", + "frexp\n", + "fsum\n", + "gamma\n", + "gcd\n", + "hypot\n", + "inf\n", + "isclose\n", + "isfinite\n", + "isinf\n", + "isnan\n", + "isqrt\n", + "ldexp\n", + "lgamma\n", + "log\n", + "log10\n", + "log1p\n", + "log2\n", + "modf\n", + "nan\n", + "perm\n", + "pi\n", + "pow\n", + "prod\n", + "radians\n", + "remainder\n", + "sin\n", + "sinh\n", + "sqrt\n", + "tan\n", + "tanh\n", + "tau\n", + "trunc\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "print(*dir(math), sep='\\n')" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.5707963267948966\n", + "1.5707963267948966\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "print(math.pi/2)\n", + "print(math.asin(1))\n", + "# 1.570796... = pi/2" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "22\n", + "21\n" + ] + } + ], + "source": [ + "# 21.33 ceil - 22\n", + "# 21.33 floor - 21\n", + "# 21, 21.33, 22\n", + "print(math.ceil(21.33))\n", + "print(math.floor(21.33))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "8.0" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "math.pow(2, 3) # 2 ** 3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$\\mathit{^5P_2}$" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "math.perm(5, 2) # 5P2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$\\mathit{^5C_2}$" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "math.comb(5, 2) # 5C2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## cmath:\n", + "Like math, used to work with complex numbers." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__doc__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "acos\n", + "acosh\n", + "asin\n", + "asinh\n", + "atan\n", + "atanh\n", + "cos\n", + "cosh\n", + "e\n", + "exp\n", + "inf\n", + "infj\n", + "isclose\n", + "isfinite\n", + "isinf\n", + "isnan\n", + "log\n", + "log10\n", + "nan\n", + "nanj\n", + "phase\n", + "pi\n", + "polar\n", + "rect\n", + "sin\n", + "sinh\n", + "sqrt\n", + "tan\n", + "tanh\n", + "tau\n" + ] + } + ], + "source": [ + "import cmath\n", + "\n", + "print(*dir(cmath), sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## sys:\n", + "\n", + "Work with program execution and system." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__breakpointhook__\n", + "__displayhook__\n", + "__doc__\n", + "__excepthook__\n", + "__interactivehook__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "__stderr__\n", + "__stdin__\n", + "__stdout__\n", + "__unraisablehook__\n", + "_base_executable\n", + "_clear_type_cache\n", + "_current_frames\n", + "_debugmallocstats\n", + "_enablelegacywindowsfsencoding\n", + "_framework\n", + "_getframe\n", + "_git\n", + "_home\n", + "_xoptions\n", + "addaudithook\n", + "api_version\n", + "argv\n", + "audit\n", + "base_exec_prefix\n", + "base_prefix\n", + "breakpointhook\n", + "builtin_module_names\n", + "byteorder\n", + "call_tracing\n", + "callstats\n", + "copyright\n", + "displayhook\n", + "dllhandle\n", + "dont_write_bytecode\n", + "exc_info\n", + "excepthook\n", + "exec_prefix\n", + "executable\n", + "exit\n", + "flags\n", + "float_info\n", + "float_repr_style\n", + "get_asyncgen_hooks\n", + "get_coroutine_origin_tracking_depth\n", + "getallocatedblocks\n", + "getcheckinterval\n", + "getdefaultencoding\n", + "getfilesystemencodeerrors\n", + "getfilesystemencoding\n", + "getprofile\n", + "getrecursionlimit\n", + "getrefcount\n", + "getsizeof\n", + "getswitchinterval\n", + "gettrace\n", + "getwindowsversion\n", + "hash_info\n", + "hexversion\n", + "implementation\n", + "int_info\n", + "intern\n", + "is_finalizing\n", + "maxsize\n", + "maxunicode\n", + "meta_path\n", + "modules\n", + "path\n", + "path_hooks\n", + "path_importer_cache\n", + "platform\n", + "prefix\n", + "ps1\n", + "ps2\n", + "ps3\n", + "pycache_prefix\n", + "set_asyncgen_hooks\n", + "set_coroutine_origin_tracking_depth\n", + "setcheckinterval\n", + "setprofile\n", + "setrecursionlimit\n", + "setswitchinterval\n", + "settrace\n", + "stderr\n", + "stdin\n", + "stdout\n", + "thread_info\n", + "unraisablehook\n", + "version\n", + "version_info\n", + "warnoptions\n", + "winver\n" + ] + } + ], + "source": [ + "import sys\n", + "\n", + "print(*dir(sys), sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## os:\n", + "works with operating system" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "DirEntry\n", + "F_OK\n", + "MutableMapping\n", + "O_APPEND\n", + "O_BINARY\n", + "O_CREAT\n", + "O_EXCL\n", + "O_NOINHERIT\n", + "O_RANDOM\n", + "O_RDONLY\n", + "O_RDWR\n", + "O_SEQUENTIAL\n", + "O_SHORT_LIVED\n", + "O_TEMPORARY\n", + "O_TEXT\n", + "O_TRUNC\n", + "O_WRONLY\n", + "P_DETACH\n", + "P_NOWAIT\n", + "P_NOWAITO\n", + "P_OVERLAY\n", + "P_WAIT\n", + "PathLike\n", + "R_OK\n", + "SEEK_CUR\n", + "SEEK_END\n", + "SEEK_SET\n", + "TMP_MAX\n", + "W_OK\n", + "X_OK\n", + "_AddedDllDirectory\n", + "_Environ\n", + "__all__\n", + "__builtins__\n", + "__cached__\n", + "__doc__\n", + "__file__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "_check_methods\n", + "_execvpe\n", + "_exists\n", + "_exit\n", + "_fspath\n", + "_get_exports_list\n", + "_putenv\n", + "_unsetenv\n", + "_wrap_close\n", + "abc\n", + "abort\n", + "access\n", + "add_dll_directory\n", + "altsep\n", + "chdir\n", + "chmod\n", + "close\n", + "closerange\n", + "cpu_count\n", + "curdir\n", + "defpath\n", + "device_encoding\n", + "devnull\n", + "dup\n", + "dup2\n", + "environ\n", + "error\n", + "execl\n", + "execle\n", + "execlp\n", + "execlpe\n", + "execv\n", + "execve\n", + "execvp\n", + "execvpe\n", + "extsep\n", + "fdopen\n", + "fsdecode\n", + "fsencode\n", + "fspath\n", + "fstat\n", + "fsync\n", + "ftruncate\n", + "get_exec_path\n", + "get_handle_inheritable\n", + "get_inheritable\n", + "get_terminal_size\n", + "getcwd\n", + "getcwdb\n", + "getenv\n", + "getlogin\n", + "getpid\n", + "getppid\n", + "isatty\n", + "kill\n", + "linesep\n", + "link\n", + "listdir\n", + "lseek\n", + "lstat\n", + "makedirs\n", + "mkdir\n", + "name\n", + "open\n", + "pardir\n", + "path\n", + "pathsep\n", + "pipe\n", + "popen\n", + "putenv\n", + "read\n", + "readlink\n", + "remove\n", + "removedirs\n", + "rename\n", + "renames\n", + "replace\n", + "rmdir\n", + "scandir\n", + "sep\n", + "set_handle_inheritable\n", + "set_inheritable\n", + "spawnl\n", + "spawnle\n", + "spawnv\n", + "spawnve\n", + "st\n", + "startfile\n", + "stat\n", + "stat_result\n", + "statvfs_result\n", + "strerror\n", + "supports_bytes_environ\n", + "supports_dir_fd\n", + "supports_effective_ids\n", + "supports_fd\n", + "supports_follow_symlinks\n", + "symlink\n", + "sys\n", + "system\n", + "terminal_size\n", + "times\n", + "times_result\n", + "truncate\n", + "umask\n", + "uname_result\n", + "unlink\n", + "urandom\n", + "utime\n", + "waitpid\n", + "walk\n", + "write\n" + ] + } + ], + "source": [ + "import os\n", + "print(*dir(os), sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## itertools:\n", + "\n", + "A module containing iterators for efficient looping" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "__doc__\n", + "__loader__\n", + "__name__\n", + "__package__\n", + "__spec__\n", + "_grouper\n", + "_tee\n", + "_tee_dataobject\n", + "accumulate\n", + "chain\n", + "combinations\n", + "combinations_with_replacement\n", + "compress\n", + "count\n", + "cycle\n", + "dropwhile\n", + "filterfalse\n", + "groupby\n", + "islice\n", + "permutations\n", + "product\n", + "repeat\n", + "starmap\n", + "takewhile\n", + "tee\n", + "zip_longest\n" + ] + } + ], + "source": [ + "import itertools\n", + "\n", + "print(*dir(itertools), sep='\\n')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/OOPS.ipynb b/OOPS.ipynb new file mode 100644 index 0000000..253f6dc --- /dev/null +++ b/OOPS.ipynb @@ -0,0 +1,457 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "source": [ + "\r\n", + "# Object Oriented Programming - Part 1\r\n", + "\r\n", + "## OOP\r\n", + "\r\n", + "Object Oriented Programming or OOP is working with classes and objects. It involves interaction between objects having various attributes.\r\n", + "\r\n", + "Python is a object oriented programming language. This means that all the types are representation or instance of a type class." + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## Components\r\n", + "\r\n", + "1. Class\r\n", + "2. Object\r\n" + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## Class\r\n", + "\r\n", + "It is a structure, a blueprint or a building block (a code block) representing or defining the attributes (features and behaviour) of similar parameters.\r\n", + "\r\n", + "### Definition\r\n", + "\r\n", + "Using `class` keyword.\r\n", + "Name of a class should start with an uppercase letter.\r\n", + "\r\n", + "Syntax:\r\n", + "\r\n", + "```python\r\n", + "class Class_name\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 1, + "source": [ + "class Students:\r\n", + " roll_no = int()\r\n", + " name = str()" + ], + "outputs": [], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## Object\r\n", + "\r\n", + "It is an instance of a class.\r\n", + "\r\n", + "Syntax: \r\n", + "\r\n", + "```python\r\n", + "obj_name = Class_name()\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 2, + "source": [ + "student1 = Students() # creating a new object\r\n", + "\r\n", + "student1.roll_no = 1\r\n", + "student1.name = 'Prabhu'" + ], + "outputs": [], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 3, + "source": [ + "print(student1.name)\r\n", + "print(student1.roll_no)" + ], + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Prabhu\n", + "1\n" + ] + } + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## *self* Keyword\r\n", + "\r\n", + "Calls the attributes for current instance or object.\r\n", + "\r\n", + "Syntax:\r\n", + "\r\n", + "```python\r\n", + "self.attribute_name\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## Defining attributes and behavior in a class\r\n", + "\r\n", + "An object is generally defined by the follwing:\r\n", + "\r\n", + "1. Fields (variables) or Attributes\r\n", + "2. Methods (functions) or Behavior\r\n", + "\r\n", + "### Fields\r\n", + "\r\n", + "The `fields` are the variables or containers that store data used and related to an object/Class\r\n", + "\r\n", + "Types: \r\n", + "\r\n", + "1. Instance fields\r\n", + "2. Class or static fields\r\n", + "\r\n", + "#### Instance fields\r\n", + "\r\n", + "The instance fields are variables that are associated with an object, an instance of the class.\r\n", + "\r\n", + "The data they have may vary from object to object and are independent. The field of one instance cannot be accessed by the other. \r\n", + "The instance variables are accessed as follows:\r\n", + "\r\n", + "```python\r\n", + "# Inside the class using `self` keyword\r\n", + "self.instance_variable\r\n", + "\r\n", + "# Outside the class using the object name\r\n", + "object_name.instance_variable\r\n", + "```\r\n", + "\r\n", + "#### Class fields\r\n", + "\r\n", + "The class variables are variables that are common throughout the instances of the defined class and can be accessed by all of them.\r\n", + "\r\n", + "Modifying data in one object changes it for all the present instances. \r\n", + "They are accessed inside and outside the class definition as follows:\r\n", + "\r\n", + "```python\r\n", + "# Using class name to access static variables\r\n", + "Class_name.class_variable\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 1, + "source": [ + "class Student_details:\r\n", + " student_count = 0\r\n", + " def __init__(self, name):\r\n", + " self.name = name # Instance variable\r\n", + " Student_details.student_count += 1 # Class Variable\r\n", + "\r\n", + "s = Student_details(\"Prabhu\")\r\n", + "print(s.name) # Instance variable\r\n", + "s1 = Student_details(\"Mano\")\r\n", + "print(s1.name) # Instance variable\r\n", + "print(Student_details.student_count) # Class variable" + ], + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Prabhu\n", + "Mano\n", + "2\n" + ] + } + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "### Methods\r\n", + "\r\n", + "The `methods` are block of code that, like functions, execute a specific task\r\n", + "\r\n", + "Though a method and function are defined in the same way, they have differences.\r\n", + "\r\n", + "A **function** is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.\r\n", + "\r\n", + "A **method** is a piece of code that is called by a name that is associated with an object. \r\n", + "\r\n", + "In most respects it is identical to a function except for two key differences:\r\n", + "\r\n", + "1. A method is implicitly passed the object on which it was called.\r\n", + "2. A method is able to operate on data that is contained within the class \r\n", + "\r\n", + "(remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).\r\n", + "\r\n", + "Source: [What's the difference between a method and a function? - StackOverflow](https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function#155655)\r\n", + "\r\n", + "Types:\r\n", + "\r\n", + "1. Instance methods\r\n", + "2. Static methods\r\n", + "\r\n", + "#### Instance methods\r\n", + "\r\n", + "Instance methods are methods/behavior that are associated with objects. When an object calls one of its instnace methods, the instance method gets implicitly passed object and uses the data it gets with other required parameters to do the task. \r\n", + "Definition and access:\r\n", + "\r\n", + "```python\r\n", + "# Definition\r\n", + "def instance_method(self[, ...]): # the self keyword indicates the implicit passing of the object\r\n", + " # Statements\r\n", + "\r\n", + "# access inside the class (in another instance method)\r\n", + "self.instance_method(...)\r\n", + "\r\n", + "# Access outside the class\r\n", + "obj.instance_method(...)\r\n", + "```\r\n", + "\r\n", + "***Note:*** It is to be noted that an instance method can be called only inside another instance method\r\n", + "\r\n", + "#### Static or Class method\r\n", + "\r\n", + "A static method is a method that is common for all objects. It is equivalent of function being defined outside the class.\r\n", + "\r\n", + "A static method is identified by the decorator `@staticmethod` and has implicit object passing using `self` keyword.\r\n", + "\r\n", + "Definition and Access:\r\n", + "\r\n", + "```python\r\n", + "@staticmethod\r\n", + "def class_method([...]):\r\n", + " #Statement(s)\r\n", + "\r\n", + "# accessing the method using class name\r\n", + "Class_name.class_method([...])\r\n", + "```\r\n", + "\r\n", + "The static method can be called inside another static method or instance method(s)\r\n" + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "### Constructor\r\n", + "\r\n", + "A method that executes a set of code whenever a new object/instance is created.\r\n", + "\r\n", + "Defined as `__new__()`. Generally, this is not defined/overridden and follows the default definition as in the `object` class\r\n", + "\r\n", + "```python\r\n", + "def __new__(cls, *args, **kwargs):\r\n", + " # Custom constructor\r\n", + "```\r\n", + "\r\n", + "### Initializer\r\n", + "\r\n", + "An instance method that initializes the object (instance) created by call with the parameters passed. \r\n", + "\r\n", + "The `__new__()` method calls this automatically.\r\n", + "\r\n", + "Defined as `__init__()`.\r\n", + "\r\n", + "```python\r\n", + "def __init__(self, *args, **kwargs):\r\n", + " # Statements for object Initialization\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 7, + "source": [ + "class Student:\r\n", + " def __init__(self): # default constructor\r\n", + " self.roll_no = 0\r\n", + " self.name = 'Name'\r\n", + "# print('__init__ file')\r\n", + " \r\n", + " def study(self):\r\n", + " print('Studying....')" + ], + "outputs": [], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 8, + "source": [ + "st1 = Student()\r\n", + "st1.roll_no = 1\r\n", + "st1.name = 'Ravi'\r\n", + "print(f'Roll No: {st1.roll_no}, Name: {st1.name}')" + ], + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "__init__ file\n", + "Roll No: 1, Name: Ravi\n" + ] + } + ], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 2, + "source": [ + "class Student_details:\r\n", + " def __init__(self, rn = 0, st_name = 'Name'): # Parametric Constructor\r\n", + " self.roll_no = rn\r\n", + " self.name = st_name\r\n", + " # print('__init__ file')\r\n", + " \r\n", + " def study(self):\r\n", + " print('Studying....')\r\n", + " @staticmethod\r\n", + " def work():\r\n", + " print(\"Working...\")" + ], + "outputs": [], + "metadata": {} + }, + { + "cell_type": "code", + "execution_count": 3, + "source": [ + "st2 = Student_details(2, 'Rahul')\r\n", + "print(f'Roll No: {st2.roll_no}, Name: {st2.name}')\r\n", + "Student_details.work()" + ], + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Roll No: 2, Name: Rahul\n", + "Working...\n" + ] + } + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## destructor\r\n", + "\r\n", + "Delete the current instance of class or object. It has default definition in the object Base class\r\n", + "\r\n", + "Use `__del__()` method to override it\r\n", + "\r\n", + "```python\r\n", + "def __del__(self, *args, **kwargs):\r\n", + " # Custom destructor\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## Some other methods\r\n", + "\r\n", + "1. \\_\\_repr\\_\\_ - String representation\r\n", + "2. \\_\\_cmp\\_\\_ - Compare two objects\r\n", + "3. \\_\\_len\\_\\_ - length of object\r\n", + "4. \\_\\_lt\\_\\_ - less than\r\n", + "5. \\_\\_le\\_\\_ - less than or equal\r\n", + "6. \\_\\_gt\\_\\_ - greater than\r\n", + "7. \\_\\_ge\\_\\_ - greater than or equal\r\n", + "8. \\_\\_ne\\_\\_ - not equal\r\n", + "9. \\_\\_eq\\_\\_ - equal\r\n", + "10. \\_\\_getitem\\_\\_ - get a key from a iterable\r\n", + "11. \\_\\_setitem\\_\\_ - set a value to the given key of iterable\r\n" + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "## Private variables and methods\r\n", + "\r\n", + "Start with \\_\\_\r\n", + "\r\n", + "E.g.: \\_\\_var, \\_\\_method\r\n", + "\r\n", + "It is advised for best programming practice to avoid calling private attributes outside the class. \r\n", + "But if needed, use the following syntax:\r\n", + "\r\n", + "```python\r\n", + "obj._classname__attribute\r\n", + "```\r\n" + ], + "metadata": {} + }, + { + "cell_type": "markdown", + "source": [ + "Check the complete example [OOPS.py](OOPS.py)\r\n", + "\r\n", + "Ignore the imports. They have been used to provide hinting about the types of each variable\r\n" + ], + "metadata": {} + } + ], + "metadata": { + "ipub": { + "subtitle": "Object Oriented Programming - Part 1/2", + "title": "Object Oriented Programming - Part 1", + "toc": true + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/OOPS.py b/OOPS.py new file mode 100644 index 0000000..c9a8d4a --- /dev/null +++ b/OOPS.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import Any, Literal, Union + + +class Student(object): + student_count: int = 0 + stud_list: dict[int, str] = dict() + __roll_no: int = 0 + name: str + club: list[Any] + + def __new__(cls, rn: int = 0, st_name: str = "Name", *clubs: Any) -> Student: + print("__new__ magic method is called to create an obj\n") + inst: Student = super().__new__(cls) + return inst + + # Parametric Constructor + def __init__(self, rn: int = 0, st_name: str = "Name", *clubs: Any) -> None: + Student.student_count += 1 + self._roll_no = rn + self.name = st_name + self.club = list(clubs) + Student.stud_list[rn] = st_name + # {_roll_no: st_name} + + def study(self) -> None: + print(f"{self.name} is Studying....") + + @staticmethod + def wake() -> str: + # self.study() + return "Woke" + + # destructor + def __del__(self) -> None: + Student.student_count -= 1 + Student.stud_list.pop(self._roll_no) + + # String representation of Object + def __repr__(self) -> str: + return f"Roll no.: {self._roll_no} \nName: {self.name}\n" f"Clubs: {self.club}" + + # Less than + def __lt__(self, obj: Student) -> bool: + return self.name < obj.name + + # Less than or equal + def __le__(self, obj: Student) -> bool: + return self.name <= obj.name + + # Greater than + def __gt__(self, obj: Student) -> bool: + return self.name > obj.name + + # Greater than or equal + def __ge__(self, obj: Student) -> bool: + return self.name >= obj.name + + # Not equal + def __ne__(self, obj: Student) -> bool: + return self.name != obj.name + + # Equal + def __eq__(self, obj: Student) -> bool: + return self.name == obj.name + + def __getitem__(self, key: int) -> str: + return self.club[key - 1] + + def __setitem__(self, key: int, value: Union[str, Literal]) -> None: + self.club[key - 1] = value + + def __len__(self) -> int: + return len(self.club) + + # getter + @property + def _roll_no(self) -> int: + # print('Getter called') + return self.__roll_no + + # setter + @_roll_no.setter + def _roll_no(self, rn: int) -> None: + # print('Setter called') + if self._roll_no in Student.stud_list.keys(): + Student.stud_list.pop(self.__roll_no) + Student.stud_list[rn] = self.name + self.__roll_no = rn + + +# Object 1 +st1 = Student(1, "Prabhu", "Coding Club", "Robotics Club") +print(st1) + +print(Student.student_count) +print(Student.stud_list, "\n") + +st1[2] = "Envy Club" +print(st1) + +st2 = Student(3, "Mano", "Coding Club", "Cyber club") +print("\n", st2, "\n", sep="") +print(Student.student_count) +print(Student.stud_list, "\n") + +st2._roll_no = 2 + +print("\n", Student.student_count, sep="") +print(Student.stud_list, "\n") + +del st2 + +print("\n", Student.student_count) +print(Student.stud_list, "\n") diff --git a/Practice_code1.ipynb b/Practice_code1.ipynb index 6164989..18eafcc 100644 --- a/Practice_code1.ipynb +++ b/Practice_code1.ipynb @@ -40,16 +40,14 @@ "\n", ">Sample 1: \n", "I/p: \n", - "Chandru \n", - "19 \n", + "Chandru 19 \n", "O/p: \n", "Chandru \n", "19 \n", "\n", ">Sample 2: \n", "I/p: \n", - "Prabhu \n", - "20 \n", + "Prabhu 20 \n", "O/p: \n", "Prabhu \n", "20 \n" @@ -395,7 +393,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.6" + "version": "3.9.6" } }, "nbformat": 4, diff --git a/Practice_code1.md b/Practice_code1.md new file mode 100644 index 0000000..8fd1339 --- /dev/null +++ b/Practice_code1.md @@ -0,0 +1,371 @@ +--- +title: Input/Output Practice questions +subtitle: Practice Code 1 +--- + +This file contains practice question for [Introduction to Python programming](Introduction_to_Python_Programming.ipynb) (input ad output) + +Try working online at: +[Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) +[Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) + +--- + +**Q1:** Write a program to print 'Hello World' + +--- + +**Q2:** Write a program to get Name from the user and print it. + +> **Sample 1:** +> I/p: Chandru +> O/p: Chandru + +
+>**Sample 2:** +I/p: Prabhu +O/p: Prabhu + +--- + +**Q3:** Write a program to get Name and age from user and print it. + +> **Sample 1:** +> I/p: +> Chandru 19 +> O/p: +> Chandru +> 19 + +
+>**Sample 2:** +I/p: +Prabhu 20 +O/p: +Prabhu +20 + +--- + +**Q4:** Write a program to get two numbers from user and print their sum + +> **Sample 1:** +> I/p: +> 12 +> 12 +> O/p: +> 24 + +
+>**Sample 2:** +I/p: +10 +15 +O/p: +25 + +--- + +**Q5:** Write a program to get two numbers and perform all arithmetic operations on them. + +--- + +**Q6:** (Update of **Q4**) +Print formatted output + +> **Sample 1:** +> I/p: +> 12 +> 12 +> O/p: +> Sum of 12 and 12 is 24 + +
+>**Sample 2:** +I/p: +10 +15 +O/p: +Sum of 10 and 15 is 25 + +--- + +**Q6:** (Update of **Q4**) +Print formatted output + +> **Sample 1:** +> I/p: +> 12 +> 12 +> O/p: +> Sum of 12 and 12 is 24 + +
+>**Sample 2:** +I/p: +10 +15 +O/p: +Sum of 10 and 15 is 25 + +--- + +**Q7:** Write a program to get name from the user and wish them Good Morning + +> **Sample:** +> I/p: Jenyhin +> O/p: Good Morning, Jenyhin + +--- + +**Q8:** Write a program to get the side of the square and print its perimeter +$\text{Perimeter of a square} = 4 \times \rm{side}$ + +> **Sample 1:** +> I/p: 4 +> O/p: 16 + +
+>**Sample 2:** +I/p: 22 +O/p: 88 + +--- + +**Q9:** Write a program to get the side of the square and print its area +$\text{Area of square} = \rm{side} \times \rm{side}$ + +> **Sample 1:** +> I/p: 4 +> O/p: 16 + +
+>**Sample 2:** +I/p: 22 +O/p: 484 + +--- + +**Q10:** Write a program to get the length and breadth of a rectangle and print its perimeter +$\text{Perimeter of a rectangle} = 2 \times \rm{(length + breadth)}$ + +> **Sample 1:** +> I/p: +> 4
+> 4 +> O/p: 16 + +
+ +> **Sample 2:** +> I/p: +> 22 +> 21 +> O/p: 86 + +--- + +**Q11:** Write a program to get the length and breadth of a rectangle and print its area +$\text{Area of a rectangle} = \text{length} \times \text{breadth}$ + +> **Sample 1:** +> I/p: +> 4
+> 4 +> O/p: 16 + +
+ +> **Sample 2:** +> I/p: +> 22 +> 21 +> O/p: 462 + +--- + +**Q12:** Write a program to get the number of sides and length of each side of a regular polygon and print its perimeter. +$\text{Perimeter} = \text{number of sides} \times \text{length of one side}$ + +> **Sample 1:** +> I/p: +> 8
+> 4 +> O/p: 32 + +
+ +> **Sample 2:** +> I/p: +> 7
+> 21 +> O/p: 147 + +--- + +**Q13:** Write a program to get the length and height of a right triangle and print its area. +$\text{Area of right triangle} = \dfrac{1}{2} \times \rm{base} \times \rm{height}$ + +> **Sample 1:** +> I/p: +> 4
+> 4 +> O/p: 8.0 + +
+ +> **Sample 2:** +> I/p: +> 22 +> 21 +> O/p: 231.0 + +--- + +**Q14:** Write a program to get the radius of a circle and print its perimeter rounded off to 3 decimal places. (Take $\pi = 3.14159$) +$\text{Perimeter of a circle} = 2\pi \times \rm{radius}$ + +> **Sample 1:** +> I/p: +> 4
+> O/p: 25.133 + +
+ +> **Sample 2:** +> I/p: +> 22 +> O/p: 138.230 + +--- + +**Q15:** Write a program to get the radius of a circle and print its area rounded off to 3 decimal places. (Take $\pi = 3.14159$) +$\text{Area of a circle} = \pi \times \rm{radius}^2$ + +> **Sample 1:** +> I/p: +> 4
+> O/p: 50.265 + +
+ +> **Sample 2:** +> I/p: +> 21 +> O/p: 1385.442 + +--- + +**Q16:** Write a program to get the sides of a triangle and print its area using Heron's Formula rounded off to 3 decimal places. +$\text{Area of right triangle} = \sqrt{s \times (s-a)\times(s-b)\times(s-c)}$ +$\rm{where},$ +$s = \text{Semi-Perimeter} = \dfrac{\text{Perimeter of triangle}}{2}$ +$a, ~b, ~c = \text{Sides of the triangle}$ + +> **Sample 1:** +> I/p: +> 3
+> 4
+> 5 +> O/p: 6.0 + +
+ +> **Sample 2:** +> I/p: +> 12 +> 21 +> 30 +> O/p: 98.359 + +--- + +**Q17:** Write a program to get the side of a equilateral triangle and print its area rounded off to 4 decimal places. +$\text{Area of equilateral triangle} = \dfrac{\sqrt{3}}{4} \times \rm{side}^2$ + +> **Sample 1:** +> I/p: +> 4
+> O/p: 6.9282 + +
+ +> **Sample 2:** +> I/p: +> 31 +> O/p: 416.1252 + +--- + +**Q18:** Write a program to get the length and height of a right triangle and print the length of its hypotenuse rounded off to 3 decimal places using Pythagoras Theorem. +From Pythagoras theorem, $ \rm{hypotenuse} = \sqrt{\rm{base}^2 + \rm{height}^2}$ + +> **Sample 1:** +> I/p: +> 3
+> 4 +> O/p: 5 + +
+ +> **Sample 2:** +> I/p: +> 12 +> 6
+> O/p: 13.416 + +--- + +**Q19:** Write a program to get the side of a cube and print its volume. +$\text{Volume of cube} = \rm{side}^3$ + +> **Sample 1:** +> I/P: 15 +> O/P: 3375 + +--- + +**Q20:** Write a program to get the side of a cube and print its total surface area. +$ \text{T.S.A of Cube} = 6 \times \rm{side}^2$ + +> **Sample 1:** +> I/P: 15 +> O/P: 1350 + +--- + +**Q21:** Write a program to get the side of a cube and print its Lateral surface area. +$\text{L.S.A of cube} = 4 \times \rm{side}^2$ + +--- + +**Q22:** Write a program to get the length, breadth and height of a cuboid and print its volume. +$\text{Volume of Cuboid} = \rm{length} \times \rm{breadth} \times \rm{height}$ + +> **Sample 1:** +> I/P: +> 43 +> 28 +> 35 +> O/P: 42140 + +--- + +**Q23:** Write a program to get the length, breadth and height of a cuboid and print its Total Surface Area. +$\text{T.S.A of Cuboid} = 2 \times ( (\rm{length} \times \rm{breadth}) + (\rm{breadth} \times \rm{height}) + (\rm{height} \times \rm{length}))$ + +> **Sample 1:** +> I/P: +> 43 +> 28 +> 35 +> O/P: 7378 + +--- + +**Q24:** Write a program to get the length, breadth and height of a cuboid and print its Lateral Surface Area. +$\text{L.S.A of Cuboid} = 2 \times \rm{height} \times (\rm{breadth}+ \rm{length})$ + +--- + +**[Check Solution](Solution1.ipynb)** diff --git a/Practice_code2.md b/Practice_code2.md index 6869307..cd9fdf9 100644 --- a/Practice_code2.md +++ b/Practice_code2.md @@ -1,81 +1,122 @@ +--- +title: Condition Statements practice +subtitle: Practice code 2 +--- + This Notebook Contains practice question for the note on [Condition statements](Condition_Statements.ipynb). Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) -**Q1:** Write a program to get a number as input and print if it is odd or even. ->Sample1: -I/P: 10 -O/P: Even +--- + +**Q1:** Write a program to get a number as input and print if it is odd or even. ->Sample 2: +> **Sample 1:** +> I/P: 10 +> O/P: Even + +
+>**Sample 2:** I/P: 11 O/P: Odd -**Q2:** Write a program to get a number as input and check whether it is positive, negative or zero. ->Sample1: -I/P: 10 -O/P: Positive +--- + +**Q2:** Write a program to get a number as input and check whether it is positive, negative or zero. ->Sample2: +> **Sample 1:** +> I/P: 10 +> O/P: Positive + +
+>**Sample 2:** I/P: 0 O/P: Zero ->Sample3: +
+>**Sample 3:** I/P: -5 O/P: Negative -**Q3:** Write a program to get the mark of a student as input print his grade. +--- -**Condition:** -mark<0 or mark>100: Invalid -90Sample1: -I/P: 85 -O/P: A+ +**Condition:** ->Sample2: +``` +mark < 0 or mark > 100: Invalid +90 < mark <= 100: O +80 < mark <= 90 : A+ +70 < mark <= 80 : A +60 < mark <= 70 : B+ +50 <= mark <= 60: B + 0 <= mark < 50: Fail +``` + +> **Sample 1:** +> I/P: 85 +> O/P: A+ + +
+>**Sample 2:** I/P: 10 O/P: Fail -**Q4:** Write a program to get the age of the user and print if he is eligible to vote. +--- + +**Q4:** Write a program to get the age of the user and print if he is eligible to vote. + **Condition:** -A person is elgible to vote if his/her age is greater than or qual to 18 ->Sample1: -I/P: 10 -O/P: Ineligible +A person is eligible to vote if his/her age is greater than or equal to 18 ->Sample2: +> **Sample 1:** +> I/P: 10 +> O/P: Ineligible + +
+>**Sample 2:** I/P: 27 O/P: Eligible +--- + **Q5:** Code a simple Calculator. +--- + **Q6:** Write a program to get an input from the user and print if it is a vowel or a consonant. +--- + **Q7:** Write a program to two numbers and print the greatest of them. +--- + **Q8:** Write a program to get three numbers and the print the greatest of them. +--- + **Q9:** Write a program to check if a number is a perfect square or not. -**Q10:** The humidity (in percentage) and temperature (in celsius) value in a city is given as the input to the program. The program must print ***YES*** as the output if there is a possibility of rain. Else the program must print ***NO*** as the output. If one of the conditions given below is true then there is a possibility of rain. +--- + +**Q10:** The humidity (in percentage) and temperature (in celsius) value in a city is given as the input to the program. The program must print **_YES_** as the output if there is a possibility of rain. Else the program must print **_NO_** as the output. If one of the conditions given below is true then there is a possibility of rain. + +_Condition:_ -*Condition:* -1. Humidity > 90 -2. Temperature < 18 -3. Humidity > 70 and Temperature < 30 +1. Humidity > 90 +2. Temperature < 18 +3. Humidity > 70 and Temperature < 30 4. Humidity > 60 and Temperature < 24 +--- + **Q11:** Write a program to get a year as input and print if it is a leap year or not. -A year is leap if it is either divisible *4* or *400* and not *100*. +A year is leap if it is either divisible _4_ or _400_ and not _100_. + +--- -**** -**[Check Solution](Solution2.ipynb)** \ No newline at end of file +**[Check Solution](Solution2.ipynb)** diff --git a/Practice_code3.md b/Practice_code3.md index 40d453e..780f957 100644 --- a/Practice_code3.md +++ b/Practice_code3.md @@ -1,77 +1,132 @@ +--- +title: Looping Practice +subtitle: Practice Code 3 +--- + This Notebook Contains practice question for the note on [Looping Statements](Looping_Statements.ipynb). Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) -**Q1:** Write a program to get the value of ***n*** from the user and print sum of ***n*** natural numbers as output. +--- + +**Q1:** Write a program to get the value of **_n_** from the user and print sum of **_n_** natural numbers as output. + +--- + +**Q2:** Write a program to get the values of **_n_** and **_n_** numbers from the user and print sum of the **_n_** numbers as output. +Input: + +First line contains the number **_n_** +Next n lines contain **_n_** integers -**Q2:** Write a program to get the values of ***n*** and ***n*** numbers from the user and print sum of the ***n*** numbers as output. -I/p: -First line contains the number ***n*** -Next n lines contain ***n*** integers -O/p: +Output: Sum of n numbers ->Sample1: -I/P: -10
-1
-5
-7 -22 -20 -40 -2
-53 -18 --1
-O/p: 167 + +> **Sample 1:** +> I/P: +> 10
+> 1
+> 5
+> 7 +> 22 +> 20 +> 40 +> 2
+> 53 +> 18 +> -1
+> O/p: 167 + +--- **Q3:** Write a program get a number from user and print if it is prime or composite. +--- + **Q4:** Write a program to get a number from the user and print its factorial as output. -**Q5:** Write a program to get the value of ***n*** from the user and print the first ***n*** terms of the Fibonacci series as output. +--- -**Q6:** Write a program to get a number ***n*** from the user and print its reverse as output. +**Q5:** Write a program to get the value of **_n_** from the user and print the first **_n_** terms of the Fibonacci series as output. + +--- + +**Q6:** Write a program to get a number **_n_** from the user and print its reverse as output. + +--- + +**Q7:** Write a program to get a number and check if it is an armstrong number or not. + +**Condition:** Armstrong / Narcissistic number is the number in any given number base, which forms the total of the same number, when each of its digits is raised to the power of the number of digits in the number. + +> **Sample 1:** +> I/P: +> 153 +> O/P: +> Armstrong Number -**Q7:** Write a program to get a number and check if it is an armstrong number or not. -**Condition:** A number is armstrong number if sum of cubes of its digit is equal to the number itself. ->Sample1: -I/P: -153 -O/P: -Armstrong Number **Explanation:** $ 1^3 + 5^3 + 3^3 = 153 $ -**Q8:** Write a program to get a number ***n*** and print its multiplication table from 1 to 20. +
+>**Sample 2:** +I/P: +407 +O/P: +Armstrong Number +**Explanation:** $ 4^3 + 0^3 + 7^3 = 407 $ -**Q9:** Write a program to get the values of ***n*** and ***n*** numbers from the user and print average of the ***n*** numbers rounded off to 4 decimal places as output. -I/p: -First line contains the number ***n*** -Next n lines contain ***n*** integers -O/p: -Average of n numbers ->Sample1: +
+>**Sample 3:** I/P: -10
-1
-5
-7 -22 -20 -40 -2
-53 -18 --1
-O/p: 16.7 - -**Q10:** Write a program to get a number ***n*** and print the ***nth*** term of Fibonacci series as output. +107 +O/P: +Not an Armstrong Number + +--- + +**Q8:** Write a program to get a number **_n_** and print its multiplication table from 1 to 20. + +--- + +**Q9:** Write a program to get the values of **_n_** and **_n_** numbers from the user and print average of the **_n_** numbers rounded off to 4 decimal places as output. +Input: + +First line contains the number **_n_** +Next n lines contain **_n_** integers + +Output: + +Average of n numbers + +> **Sample 1:** +> I/P: +> 10
+> 1
+> 5
+> 7 +> 22 +> 20 +> 40 +> 2
+> 53 +> 18 +> -1
+> O/p: 16.7 + +--- + +**Q10:** Write a program to get a number **_n_** and print the **_nth_** term of Fibonacci series as output. + +--- **Q11:** Write a program to get two numbers as input and print their **HCF** as output. +--- + **Q12:** Write a program to get two numbers as input and print their **LCM** as output. -**** -**[Check Solution](Solution3.ipynb)** \ No newline at end of file +--- + +**[Check Solution](Solution3.ipynb)** diff --git a/Practice_code4.md b/Practice_code4.md index 620cce4..668f9a2 100644 --- a/Practice_code4.md +++ b/Practice_code4.md @@ -1,60 +1,109 @@ +--- +title: Practice Functions +subtitle: Practice Code 4 +--- + This Notebook Contains practice question for the note on [Functions](Functions.ipynb). Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) -**Q1:** Write a program to define a function ***multiply*** which get two parameters and returns the product of them. +--- + +**Q1:** Write a program to define a function **_multiply_** which get two parameters and returns the product of them. + +--- **Q2:** Write a program to create a function that gets sides of a rectangle and return its perimeter and area. -**Q3:** Write a program to create a function that gets a number ***n*** and a value and prints the value ***n*** times as output. ->Sample1: -I/P: -10
-Hello -O/p: -Hello -Hello -Hello -Hello -Hello -Hello -Hello -Hello -Hello -Hello - ->Sample2: +--- + +**Q3:** Write a program to create a function that gets a number **_n_** and a value **_s_** and prints the value **_n_** times as output. + +> **Sample 1:** +> I/P: +> 10
+> Hello +>
+> O/P: +> Hello +> Hello +> Hello +> Hello +> Hello +> Hello +> Hello +> Hello +> Hello +> Hello + +
+>**Sample 2:** I/P: 5
1
-O/p: +
+O/P: 1
1
1
1 -1 +1 + +--- **Q4:** Write a program to define a function to determine simple interest for given values of Principal, Rate p.a. and duration in years. Simple Interest, S.I. = $\dfrac{P \times R \times T}{100}$ -**Q5:** Write a program to get a number ***n*** and and print the prime numbers from 1 to ***n***. Use function to check if a number is prime or not. +--- + +**Q5:** Write a program to get a number **_n_** and and print the prime numbers from 1 to **_n_**. Use function to check if a number is prime or not. + +--- **Q6:** Write a program to define a function to return factorial of the number passed in it (use recursion). -**Q6:** Write a program to define a function to return factorial of the number passed in it (without recursion). +--- + +**Q7:** Write a program to define a function to return factorial of the number passed in it (without recursion). + +--- + +**Q8:** Write a program to define a function that gets a year as input and print if it is a leap year or not. + +**Condition:** A year is leap if it is either divisible _4_ or _400_ and not _100_. + +--- + +**Q9:** Write a program to define a function that returns the permutation of **_n_** and **_r_**.
+$\text{Permutation(n, r)} = {}^nP_r = \dfrac{n!}{(n-r)!}$ + +--- + +**Q10:** Write a program to define a function that returns the permutation of **_n_** and **_r_**. Use recursion to compute the factorials.
+$\text{Permutation(n, r)} = {}^nP_r = \dfrac{n!}{(n-r)!}$ + +--- + +**Q11:** Write a program to define a function that returns the permutation of **_n_** and **_r_**.
+$\text{Permutation(n, r)} = {}^nP_r$ = $\dfrac{n!}{(n-r)!} = n(n-1)(n-2)...r ~\text{terms}$ + +--- + +**Q12:** Write a program to define a function that returns the combination of **_n_** and **_r_**.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!}$ -**Q7:** Write a program to define a function that returns the permutation of ***n*** and ***r***.
-Permutation(n,r) = $^nP_r$ = $\dfrac{n!}{(n-r)!}$ +--- -**Q8:** Write a program to define a function that returns the caombinations of ***n*** and ***r***.
-Permutation(n,r) = $^nC_r$ = $\dfrac{n!}{(n-r)!~r!}$ +**Q13:** Write a program to define a function that returns the combinations of **_n_** and **_r_**. Use recursion to compute the factorials.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!}$ -**Q9:** Write a program to define a function that gets a year as input and print if it is a leap year or not. -**Condition:** A year is leap if it is either divisible *4* or *400* and not *100*. +--- +**Q14:** Write a program to define a function that returns the combinations of **_n_** and **_r_**.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!} = \dfrac{n(n-1)(n-2)...r ~\text{terms}}{1 \times 2 \times 3... r ~\text{(r terms)}} = \displaystyle \prod_{i ~= ~0}^{r ~-~1} \dfrac{n-i}{i+1}$ +--- -**** -**[Check Solution](Solution4.ipynb)** \ No newline at end of file +**[Check Solution](Solution4.ipynb)** diff --git a/Practice_code5.md b/Practice_code5.md index fd9010e..18382cf 100644 --- a/Practice_code5.md +++ b/Practice_code5.md @@ -1,185 +1,257 @@ +--- +title: List DS Practice +subtitle: Practice Code 5 +--- + This Notebook Contains practice question for the note on [Lists](DS_Lists.ipynb). Try working online at: [Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) [Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) -**Q1:** Write a program to get a number ***n*** and ***n*** numbers as input and print them as a list. ->Sample 1: -I/p: -3
-5
-2
--20 -O/p: -[5, 2, -20] +--- + +**Q1:** Write a program to get a number **_n_** and **_n_** numbers as input and print them as a list. + +> **Sample 1:** +> I/p: +> 3
+> 5
+> 2
+> -20 +> O/p: +> [5, 2, -20] + +--- **Q2:** Get the list of integers as input, sort them and print as output. ->Sample 1: -I/P: --1 110 -10 0 20 1 60 -O/P: -[-10 -1 0 1 20 60 110] + +> **Sample 1:** +> I/P: +> -1 110 -10 0 20 1 60 +> O/P: +> [-10 -1 0 1 20 60 110] + +--- **Q3:** Get a list of integers as input and print the even elements present in it. (No. of even elements > 1) -> Sample 1: -I/P: 10 20 5 -2 79 23335 40 -O/p: [10 20 -2 40] -**Q4:** Write a program to get a list of integers and print their product as output. (Use *reduce* method). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 13202000 +> **Sample 1:** +> I/P: 10 20 5 -2 79 23335 40 +> O/p: [10 20 -2 40] + +--- + +**Q4:** Write a program to get a list of integers and print their product as output. (Use _reduce_ method). -**Q5:** Write a program to get a list of integers and print their sum as output. (Use *sum* method). > Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 90 +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 13202000 + +--- + +**Q5:** Write a program to get a list of integers and print their sum as output. (Use _sum_ method). + +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 90 + +--- **Q6:** Write a program to get a list of integers and print their sum as output. (use loops). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 90 + +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 90 + +--- **Q7:** Write a program to get a list of integers and print their product as output. (Use loops). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 13202000 + +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 13202000 + +--- **Q8:** Write a program to get a list of integers and print their average as output. (round off to 3 decimal places). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 12.857 -**Q9:** Write a program to get a list of integers and print the maximum value as output. (Use *max* method). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 41 +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 12.857 + +--- + +**Q9:** Write a program to get a list of integers and print the maximum value as output. (Use _max_ method). + +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 41 + +--- **Q10:** Write a program to get a list of integers and print the maximum value as output. (Use loops). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: 41 -**Q11:** Write a program to get a list of integers and print the minimum value as output. (Use *min* method). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: -7 +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: 41 + +--- + +**Q11:** Write a program to get a list of integers and print the minimum value as output. (Use _min_ method). + +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: -7 + +--- **Q12:** Write a program to get a list of integers and print the minimum value as output. (Use loops). -> Sample 1: -I/P: 10 20 5 41 -2 -7 23 -O/P: -7 -**Q13:** Write a program to get a number ***n*** and print first ***n*** terms of Fibonacci series. +> **Sample 1:** +> I/P: 10 20 5 41 -2 -7 23 +> O/P: -7 + +--- + +**Q13:** Write a program to get a number **_n_** and print first **_n_** terms of Fibonacci series. + +--- **Q14:** Write a program to get a list of string values as input and print the values at even position as output. -> Sample 1: -I/P: Hi First Second python STRING -O/P: First python + +> **Sample 1:** +> I/P: Hi First Second python STRING +> O/P: First python + +--- **Q15:** Write a program to get a list of numbers as input and print their median as output. -(Median is the center-most value of the sorted list) -> Sample 1: -I/P: 2 9 1 7 4 8 -O/P: 6.5 +(Median is the center-most value of the sorted list) ->Sample 2: +> **Sample 1:** +> I/P: 2 9 1 7 4 8 +> O/P: 6.5 + +
+>**Sample 2:** I/P: 1 7 8 6 3 O/P: 3 +--- + **Q16:** Write a program to get a list of numbers as input and print their mode as output. -(Mode is the most frequent value of the given list) -> Sample 1: -I/P: 2 9 1 1 4 1 -O/P: 1 +(Mode is the most frequent value of the given list) + +> **Sample 1:** +> I/P: 2 9 1 1 4 1 +> O/P: 1 ->Sample 2: +
+>**Sample 2:** I/P: 1 3 8 6 3 O/P: 3 -**Q17:** Write a program to get the number of rows ***n*** and n rows of a matrix and print each row as a list. -> Sample1: -I/P: -3
-10 20 30 -1 2 3 -5 -4 -10 -O/P: -[10, 20, 30] -[1, 2, 3] -[5, -4, -10] - -**Q18:** Write a program to get the number of rows ***n*** and *nxn* matrix and print its transpose. -> Sample1: -I/P: -3
-10 20 30 -1 2 3 -5 -4 -10 -O/P: -10 1 5 -20 2 -4 -30 3 -10 - -**Q19:** Write a program to get number of rows ***r*** and columns ***c*** and two *rxc* matrices and print their sum as output. -(No empty lines are provided in between the matrices) ->Sample 1: -4
-4
-9 13 5 2 -1 11 7 6 -3 7 4 1 -6 0 7 10

--2 4 7 31 -6 9 12 6 -12 11 0 1 -9 10 2 3

-O/P: -7 17 12 33 -7 20 19 12 -15 18 4 2 -15 10 9 13 - -**Q20:** Write a program to get number of rows ***r*** and no. of columns ***c*** and three *rxc* matrices and print their sum as output. -(No empty lines are provided in between the matrices) ->Sample 1: -4
-4
-9 13 5 2 -1 11 7 6 -3 7 4 1 -6 0 7 10

--2 4 7 31 -6 9 12 6 -12 11 0 1 -9 10 2 3

-0 2 8 6 -3 7 1 0 -0 0 1 2 -10 1 0 11

-O/P: -7 19 20 39 -10 27 20 12 -15 18 5 4 -25 11 9 24 - -**Q21:** Write a program to get a *mxn* matrix and a *pxq* matrix (m, n, p, q given) and print their product as output. +--- + +**Q17:** Write a program to get the number of rows **_n_** and n rows of a matrix and print each row as a list. + +> **Sample 1:** +> I/P: +> 3
+> 10 20 30 +> 1 2 3 +> 5 -4 -10 +> O/P: +> [10, 20, 30] +> [1, 2, 3] +> [5, -4, -10] + +--- + +**Q18:** Write a program to get the number of rows **_n_** and $n\times n$ matrix and print its transpose. + +> **Sample1:** +> I/P: +> 3
+> 10 20 30 +> 1 2 3 +> 5 -4 -10 +> O/P: +> 10 1 5 +> 20 2 -4 +> 30 3 -10 + +--- + +**Q19:** Write a program to get number of rows **_r_** and columns **_c_** and two $r \times c$ matrices and print their sum as output. +(No empty lines are provided in between the matrices) + +> **Sample 1:** +> 4
+> 4
+> 9 13 5 2 +> 1 11 7 6 +> 3 7 4 1 +> 6 0 7 10
+> -2 4 7 31 +> 6 9 12 6 +> 12 11 0 1 +> 9 10 2 3
+> O/P: +> 7 17 12 33 +> 7 20 19 12 +> 15 18 4 2 +> 15 10 9 13 + +--- + +**Q20:** Write a program to get number of rows **_r_** and no. of columns **_c_** and three $r \times c$ matrices and print their sum as output. +(No empty lines are provided in between the matrices) + +> **Sample 1:** +> 4
+> 4
+> 9 13 5 2 +> 1 11 7 6 +> 3 7 4 1 +> 6 0 7 10
+> -2 4 7 31 +> 6 9 12 6 +> 12 11 0 1 +> 9 10 2 3
+> 0 2 8 6 +> 3 7 1 0 +> 0 0 1 2 +> 10 1 0 11
+> O/P: +> 7 19 20 39 +> 10 27 20 12 +> 15 18 5 4 +> 25 11 9 24 + +--- + +**Q21:** Write a program to get a $m \times n$ matrix and a $p \times q$ matrix (m, n, p, q given) and print their product as output. (No empty lines are provided in between the matrices) ->Sample1: -3
2
--82 0 --57 -95 -91 56

-2
4
-1 3 -11 24 --59 42 -15 48

-O/P: --82 -246 902 -1968 -5548 -4161 2052 -5928 --3213 2625 -1841 4872 - -**Q22:** Write a program to get a list of words and sort them in lexicograhic order. - -***** -**[Check Solution](Solution5.ipynb)** \ No newline at end of file + +> **Sample1:** +> 3
2
+> -82 0 +> -57 -95 +> 91 56
+> 2
4
+> 1 3 -11 24 +> -59 42 -15 48
+> O/P: +> -82 -246 902 -1968 +> 5548 -4161 2052 -5928 +> -3213 2625 -1841 4872 + +--- + +**Q22:** Write a program to get a list of words and sort them in lexicographic order. + +--- + +**[Check Solution](Solution5.ipynb)** diff --git a/Practice_code6.md b/Practice_code6.md index 8a95460..66ba5e2 100644 --- a/Practice_code6.md +++ b/Practice_code6.md @@ -1,3 +1,8 @@ +--- +title: Strings Practice +subtitle: Practice Code 6 +--- + This Notebook Contains practice question for the note on [Strings](DS_Strings.ipynb). Try working online at: @@ -14,15 +19,15 @@ Try working online at: **Q5:** Write a program to get a string and print digits in them as output. -**Q6:** Write a program to get a string ***s*** and a substring ***x*** and print if the ***x*** is present in ***s*** as output. +**Q6:** Write a program to get a string **_s_** and a substring **_x_** and print if the **_x_** is present in **_s_** as output. **Q7:** Write a program to get a string and set the first letter of all the words in the string to upper case and print the modified string as output. **Q8**: Write a program to get a name from the user and print if it is a valid name as output. -**Condition:** Name is valid if contains only alphabets and there are atleast 1 uppercase and 1 lowercase characters. +**Condition:** Name is valid if contains only alphabets and there are at least 1 uppercase and 1 lowercase characters. -**Q9:** Write a program to get a variable name, replace all the whitespaces with an underscore " _ " and print the modified string as output. +**Q9:** Write a program to get a variable name, replace all the white spaces with an underscore " \_ " and print the modified string as output. **Q10:** Write a program to get a string and print all the elements sorted in the alphabetical order as output. -**Q11:** Write a program to get a string and print the words in them in lexicographic order as output. The words in the string are delimited by a single whitespace (' '). \ No newline at end of file +**Q11:** Write a program to get a string and print the words in them in lexicographic order as output. The words in the string are delimited by a single whitespace (' '). diff --git a/Practice_code7.md b/Practice_code7.md new file mode 100644 index 0000000..57c7bee --- /dev/null +++ b/Practice_code7.md @@ -0,0 +1,10 @@ +--- +title: Tuples Practice +subtitle: Practice Code 7 +--- + +This Notebook Contains practice question for the note on [Tuples](DS_Tuples.ipynb). + +Try working online at: +[Coding Ground - Tutorials Point](https://www.tutorialspoint.com/execute_python3_online.php) +[Online Compiler and Debugger](https://www.onlinegdb.com/online_python_compiler) diff --git a/README.md b/README.md index 03edcbe..be8e546 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,30 @@ This repository contains in depth notes for Python Programming. For missing content, refer [Official Documentation](https://docs.python.org/) -For some short snippets in python, visit [30 seconds of code - python](https://www.30secondsofcode.org/python/p/1) +For some short snippets in python, visit [30 seconds of code - python](https://www.30secondsofcode.org/python/p/1) +For short notes refer, [Cheat Sheet](Cheat_sheet.pdf) + +Books: + +1. A Byte of Python by Swaroopch + [Read Online](https://python.swaroopch.com) + [Download PDF or EPUB](https://github.com/swaroopch/byte-of-python/releases/latest) + [Purchase](https://swaroopch.com/buybook) + +2. Automate the Boring Stuff with Python by Al Sweigart + [Read Online](https://automatetheboringstuff.com/2e/) + [Purchase](https://www.amazon.in/Automate-Boring-Stuff-Python-2nd/dp/1593279922/ref=sr_1_3?crid=P8EQ7A13BCC7&dchild=1&keywords=automate+the+boring+stuff+with+python&qid=1622629604&sprefix=Automate+the+boring+%2Caps%2C317&sr=8-3) + +3. Beyond the Basic Stuff with Python by Al Sweigart + [Read Online](https://inventwithpython.com/beyond/) + [Purchase](https://www.amazon.in/Python-Beyond-Basics-Al-Sweigart/dp/1593279663/ref=sr_1_3?crid=3R7C1Q4GPS9WB&dchild=1&keywords=beyond+the+basic+stuff+with+python&qid=1622629740&sprefix=Beyond+the+basic+stuff+with+%2Caps%2C322&sr=8-3) + +Read the notes using [GitHub pages](https://aniruddh-0701.github.io/Python_Programming_Notes/) ### Sequence of notes: + +All the outputs are to be tested by using print statement. In the notes shared, if only names of variables/functions are given, please use print statement(s) in your code to get the output. +
  1. Installing and Using Python
  2. Introduction to Python programming
  3. @@ -14,24 +35,27 @@ For some short snippets in python, visit [30 seconds of code - python](https://w
  4. Looping statements in Python
  5. Functions in Python
  6. Data Structures - Lists
  7. -
  8. Data Stuctures - String
  9. +
  10. Data Structures - String
  11. Data Structures - Tuples
  12. -
  13. Data Structures - Dictionaries
  14. -
  15. Data Structres - Sets
  16. -
  17. Modules and Packages
  18. +
  19. Data Structures - Dictionaries
  20. +
  21. Data Structures - Sets
  22. +
  23. Errors and Exception Handling
  24. +
  25. Modules and Packages
  26. File Handling
  27. Advanced I/O
  28. -
  29. Errors and Exception Handling
  30. Python Generators
  31. Python Iterators
  32. -
  33. Object Oriented Programming in Python
  34. -
  35. Regular Expressions
  36. +
  37. Numbers in Programming
  38. +
  39. Object Oriented Programming in Python - Part I
  40. +
  41. Object Oriented Programming in Python - Part II
  42. +
  43. Regular Expressions in Python
### Test questions: + 1. [Code Practice 1](Practice_code1.ipynb); [Code Practice 1 Solution](Solution1.ipynb) 2. [Code Practice 2](Practice_code2.md); [Code Practice 2 Solution](Solution2.ipynb) 3. [Code Practice 3](Practice_code3.md); [Code Practice 3 Solution](Solution3.ipynb) 4. [Code Practice 4](Practice_code4.md); [Code Practice 4 Solution](Solution4.ipynb) -5. [Code Practice 5](Practice_code5.md); [Code Practice 5 Solution](Solution5.ipynb ) -6. [Code Practice 6](Practice_code6.md) \ No newline at end of file +5. [Code Practice 5](Practice_code5.md); [Code Practice 5 Solution](Solution5.ipynb) +6. [Code Practice 6](Practice_code6.md) diff --git a/__pycache__/prime_gen.cpython-38.pyc b/__pycache__/prime_gen.cpython-38.pyc new file mode 100644 index 0000000..b6c67e8 Binary files /dev/null and b/__pycache__/prime_gen.cpython-38.pyc differ diff --git a/__pycache__/prime_generator.cpython-38.pyc b/__pycache__/prime_generator.cpython-38.pyc new file mode 100644 index 0000000..7cdfb3a Binary files /dev/null and b/__pycache__/prime_generator.cpython-38.pyc differ diff --git a/docs/.ipynb_checkpoints/DS_Lists-checkpoint.html b/docs/.ipynb_checkpoints/DS_Lists-checkpoint.html new file mode 100644 index 0000000..b1cbdbe --- /dev/null +++ b/docs/.ipynb_checkpoints/DS_Lists-checkpoint.html @@ -0,0 +1,17189 @@ + + + + + +DS_Lists + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/.ipynb_checkpoints/Errors_and_Exception_Handling-checkpoint.html b/docs/.ipynb_checkpoints/Errors_and_Exception_Handling-checkpoint.html new file mode 100644 index 0000000..56df5f1 --- /dev/null +++ b/docs/.ipynb_checkpoints/Errors_and_Exception_Handling-checkpoint.html @@ -0,0 +1,14552 @@ + + + + + +Errors_and_Exception_Handling + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/.ipynb_checkpoints/Functions-checkpoint.html b/docs/.ipynb_checkpoints/Functions-checkpoint.html new file mode 100644 index 0000000..b5c5a08 --- /dev/null +++ b/docs/.ipynb_checkpoints/Functions-checkpoint.html @@ -0,0 +1,16099 @@ + + + + + +Functions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/.ipynb_checkpoints/Practice_code1-checkpoint.html b/docs/.ipynb_checkpoints/Practice_code1-checkpoint.html new file mode 100644 index 0000000..aeca1b8 --- /dev/null +++ b/docs/.ipynb_checkpoints/Practice_code1-checkpoint.html @@ -0,0 +1,14620 @@ + + + + + +Practice_code1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/.ipynb_checkpoints/Practice_code2-checkpoint.html b/docs/.ipynb_checkpoints/Practice_code2-checkpoint.html new file mode 100644 index 0000000..d772473 --- /dev/null +++ b/docs/.ipynb_checkpoints/Practice_code2-checkpoint.html @@ -0,0 +1,68 @@ +

This Notebook Contains practice question for the note on Condition statements.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+

Q1: Write a program to get a number as input and print if it is odd or even.

+
+

Sample1:
+I/P: 10
+O/P: Even

+

Sample 2:
+I/P: 11
+O/P: Odd

+
+

Q2: Write a program to get a number as input and check whether it is positive, negative or zero.

+
+

Sample1:
+I/P: 10
+O/P: Positive

+

Sample2:
+I/P: 0
+O/P: Zero

+

Sample3:
+I/P: -5
+O/P: Negative

+
+

Q3: Write a program to get the mark of a student as input print his grade.

+

Condition:
+mark < 0 or mark > 100: Invalid +90 < mark <= 100: O +80 < mark <= 90 : A+ +70 < mark <= 80 : A +60 < mark <= 70 : B+ +50 <= mark <= 60: B + 0 <= mark < 50: Fail

+
+

Sample1:
+I/P: 85
+O/P: A+

+

Sample2:
+I/P: 10
+O/P: Fail

+
+

Q4: Write a program to get the age of the user and print if he is eligible to vote.
+Condition: +A person is elgible to vote if his/her age is greater than or equal to 18

+
+

Sample1:
+I/P: 10
+O/P: Ineligible

+

Sample2:
+I/P: 27
+O/P: Eligible

+
+

Q5: Code a simple Calculator.

+

Q6: Write a program to get an input from the user and print if it is a vowel or a consonant.

+

Q7: Write a program to two numbers and print the greatest of them.

+

Q8: Write a program to get three numbers and the print the greatest of them.

+

Q9: Write a program to check if a number is a perfect square or not.

+

Q10: The humidity (in percentage) and temperature (in celsius) value in a city is given as the input to the program. The program must print YES as the output if there is a possibility of rain. Else the program must print NO as the output. If one of the conditions given below is true then there is a possibility of rain.

+

Condition:
+1. Humidity > 90
+2. Temperature < 18
+3. Humidity > 70 and Temperature < 30
+4. Humidity > 60 and Temperature < 24

+

Q11: Write a program to get a year as input and print if it is a leap year or not.
+A year is leap if it is either divisible 4 or 400 and not 100.

+
+

Check Solution

\ No newline at end of file diff --git a/docs/.ipynb_checkpoints/Practice_code3-checkpoint.html b/docs/.ipynb_checkpoints/Practice_code3-checkpoint.html new file mode 100644 index 0000000..6417c08 --- /dev/null +++ b/docs/.ipynb_checkpoints/Practice_code3-checkpoint.html @@ -0,0 +1,80 @@ +

This Notebook Contains practice question for the note on Looping Statements.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+

Q1: Write a program to get the value of n from the user and print sum of n natural numbers as output.

+

Q2: Write a program to get the values of n and n numbers from the user and print sum of the n numbers as output.
+I/p:
+First line contains the number n
+Next n lines contain n integers
+O/p: +Sum of n numbers

+
+

Sample1:
+I/P:
+10
+1
+5
+7
+22
+20
+40
+2
+53
+18
+-1
+O/p: 167

+
+

Q3: Write a program get a number from user and print if it is prime or composite.

+

Q4: Write a program to get a number from the user and print its factorial as output.

+

Q5: Write a program to get the value of n from the user and print the first n terms of the Fibonacci series as output.

+

Q6: Write a program to get a number n from the user and print its reverse as output.

+

Q7: Write a program to get a number and check if it is an armstrong number or not.
+Condition: Armstrong / Narcissistic number is the number in any given number base, which forms the total of the same number, when each of its digits is raised to the power of the number of digits in the number.

+
+

Sample 1:
+I/P: +153
+O/P: +Armstrong Number
+Explanation: $ 1^3 + 5^3 + 3^3 = 153 $

+

Sample 2:
+I/P:
+407
+O/P:
+Armstrong Number
+Explanation: $ 4^3 + 0^3 + 7^3 = 407 $

+

Sample 3:
+I/P:
+107 +O/P:
+Not an Armstrong Number

+
+

Q8: Write a program to get a number n and print its multiplication table from 1 to 20.

+

Q9: Write a program to get the values of n and n numbers from the user and print average of the n numbers rounded off to 4 decimal places as output.
+I/p:
+First line contains the number n
+Next n lines contain n integers
+O/p: +Average of n numbers

+
+

Sample1:
+I/P:
+10
+1
+5
+7
+22
+20
+40
+2
+53
+18
+-1
+O/p: 16.7

+
+

Q10: Write a program to get a number n and print the nth term of Fibonacci series as output.

+

Q11: Write a program to get two numbers as input and print their HCF as output.

+

Q12: Write a program to get two numbers as input and print their LCM as output.

+
+

Check Solution

\ No newline at end of file diff --git a/docs/.ipynb_checkpoints/Practice_code4-checkpoint.html b/docs/.ipynb_checkpoints/Practice_code4-checkpoint.html new file mode 100644 index 0000000..571519e --- /dev/null +++ b/docs/.ipynb_checkpoints/Practice_code4-checkpoint.html @@ -0,0 +1,55 @@ +

This Notebook Contains practice question for the note on Functions.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+

Q1: Write a program to define a function multiply which get two parameters and returns the product of them.

+

Q2: Write a program to create a function that gets sides of a rectangle and return its perimeter and area.

+

Q3: Write a program to create a function that gets a number n and a value s and prints the value n times as output.

+
+

Sample1:
+I/P:
+10
+Hello
+O/p:
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello

+

Sample2:
+I/P:
+5
+1
+O/p:
+1
+1
+1
+1
+1

+
+

Q4: Write a program to define a function to determine simple interest for given values of Principal, Rate p.a. and duration in years.
+Simple Interest, S.I. = $\dfrac{P \times R \times T}{100}$

+

Q5: Write a program to get a number n and and print the prime numbers from 1 to n. Use function to check if a number is prime or not.

+

Q6: Write a program to define a function to return factorial of the number passed in it (use recursion).

+

Q7: Write a program to define a function to return factorial of the number passed in it (without recursion).

+

Q8: Write a program to define a function that gets a year as input and print if it is a leap year or not.
+Condition: A year is leap if it is either divisible 4 or 400 and not 100.

+

Q9: Write a program to define a function that returns the permutation of n and r.
+Permutation(n,r) = $^nP_r$ = $\dfrac{n!}{(n-r)!}$

+

Q10: Write a program to define a function that returns the permutation of n and r. Use recursion to compute the factorials.
+Permutation(n,r) = $^nP_r$ = $\dfrac{n!}{(n-r)!}$

+

Q11: Write a program to define a function that returns the permutation of n and r.
+Permutation(n,r) = $^nP_r$ = $\dfrac{n!}{(n-r)!} = n(n-1)(n-2)...r ~\text{terms}$

+

Q12: Write a program to define a function that returns the combination of n and r.
+Combination(n,r) = $^nC_r$ = $\dfrac{n!}{(n-r)!~r!}$

+

Q13: Write a program to define a function that returns the combinations of n and r. Use recursion to compute the factorials.
+Combination(n,r) = $^nC_r$ = $\dfrac{n!}{(n-r)!~r!}$

+

Q14: Write a program to define a function that returns the combinations of n and r.
+Combination(n,r) = $^nC_r$ = $\dfrac{n!}{(n-r)!~r!} = \dfrac{n(n-1)(n-2)...r ~\text{terms}}{1 \times 2 \times 3... r ~\text{(r terms)}} = \displaystyle \prod_{i ~= ~0}^{r ~-~1} \dfrac{n-i}{i+1}$

+
+

Check Solution

\ No newline at end of file diff --git a/docs/.ipynb_checkpoints/README-checkpoint.md b/docs/.ipynb_checkpoints/README-checkpoint.md new file mode 100644 index 0000000..20ca025 --- /dev/null +++ b/docs/.ipynb_checkpoints/README-checkpoint.md @@ -0,0 +1,56 @@ +# Python Programming Notes + + + +This repository contains in depth notes for Python Programming. +For missing content, refer [Official Documentation](https://docs.python.org/) +For some short snippets in python, visit [30 seconds of code - python](https://www.30secondsofcode.org/python/p/1) +For short notes refer, [Cheat Sheet](Cheat_sheet.pdf) + +Books: + +1. A Byte of Python - Swaroopch +[Read Online](https://python.swaroopch.com) +[Download PDF or EPUB](https://github.com/swaroopch/byte-of-python/releases/latest) +[Purchase](https://swaroopch.com/buybook) + +2. Automate the Boring Stuff with Python by Al Sweigart +[Read Online](https://automatetheboringstuff.com/2e/) +[Purchase](https://www.amazon.in/Automate-Boring-Stuff-Python-2nd/dp/1593279922/ref=sr_1_3?crid=P8EQ7A13BCC7&dchild=1&keywords=automate+the+boring+stuff+with+python&qid=1622629604&sprefix=Automate+the+boring+%2Caps%2C317&sr=8-3) + +3. Beyond the Basic Stuff with Python by Al Sweigart +[Read Online](https://inventwithpython.com/beyond/) +[Purchase](https://www.amazon.in/Python-Beyond-Basics-Al-Sweigart/dp/1593279663/ref=sr_1_3?crid=3R7C1Q4GPS9WB&dchild=1&keywords=beyond+the+basic+stuff+with+python&qid=1622629740&sprefix=Beyond+the+basic+stuff+with+%2Caps%2C322&sr=8-3) + +### Sequence of notes: +All the outputs are to be tested by using print statement. In the notes shared, if only names of variables/functions are given, please use print statement(s) in your code to get the output. + +
    +
  1. Installing and Using Python
  2. +
  3. Introduction to Python programming
  4. +
  5. Decision Control Statements in Python
  6. +
  7. Looping statements in Python
  8. +
  9. Functions in Python
  10. +
  11. Data Structures - Lists
  12. +
  13. Data Stuctures - String
  14. +
  15. Data Structures - Tuples
  16. +
  17. Data Structures - Dictionaries
  18. +
  19. Data Structres - Sets
  20. +
  21. Modules and Packages
  22. +
  23. File Handling
  24. +
  25. Advanced I/O
  26. +
  27. Errors and Exception Handling
  28. +
  29. Python Generators
  30. +
  31. Python Iterators
  32. +
  33. Numbers in Programming
  34. +
  35. Object Oriented Programming in Python
  36. +
  37. Regular Expressions in Python
  38. +
+ +### Test questions: +1. [Code Practice 1](Practice_code1.html); [Code Practice 1 Solution](Solution1.html) +2. [Code Practice 2](Practice_code2.html); [Code Practice 2 Solution](Solution2.html) +3. [Code Practice 3](Practice_code3.html); [Code Practice 3 Solution](Solution3.html) +4. [Code Practice 4](Practice_code4.html); [Code Practice 4 Solution](Solution4.html) +5. [Code Practice 5](Practice_code5.html); [Code Practice 5 Solution](Solution5.html ) +6. [Code Practice 6](Practice_code6.html) diff --git a/docs/ASCII_chart.png b/docs/ASCII_chart.png new file mode 100644 index 0000000..baa0b7d Binary files /dev/null and b/docs/ASCII_chart.png differ diff --git a/docs/Advanced_IO.html b/docs/Advanced_IO.html new file mode 100644 index 0000000..ffb8073 --- /dev/null +++ b/docs/Advanced_IO.html @@ -0,0 +1,129 @@ + + + + + + + + Some Indepth concepts on I/O: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Some Indepth concepts on I/O:

+ +

I/O - Input/Output. +Input and Output are integral part of a program. This makes the program interactive (dynamic) and user friendly.

+

Input conditions and values may vary depending on situation / constraints. So handling Inputs is important.

+

Variations:

+
    +
  1. One line Input of multiple values
  2. +
+

1. One line input:

+

Multiple values can be given in one line as input which needs to be processed differently. This brings in the need for a method to work with them.

+
    +
  1. fixed type input
  2. +
  3. variable length input
  4. +
+

Generally one line input uses multiple assignment by splitting the values down (or scattering) to the required variables.
+map functions are used to assign a function or change the data type of the variables.

+

1. Fixed type:

+

In this type, the number of inputs in the line is fixed and known. A simple input statements has the required no. of variables in the LHS and input command with string splitting on the RHS.

+

2. Variable length type

+

In this type, the number of inputs in the line is variable and only minimum count is known. A simple input statements has the required no. of variables with last variable working as gather variable (with * before its name) in the LHS and input command with string splitting on the RHS.

+

IN [1]

+
# Example for two inputs
+a, b = input().split()
+print(a)
+print(b)
+# input: Hi Hello
+
+

stdin

+
 Hi Hello
+
+
+

stdout

+
Hi
+Hello
+
+
+

IN [3]

+
# Change type for input
+c, d = map(int, input().split())
+print(c, type(c), sep = '\n')
+print(d, type(d), sep = '\n')
+# Input: 10 20
+
+

stdin

+
 10 20
+
+
+

stdout

+
10
+<class 'int'>
+20
+<class 'int'>
+
+
+

IN [5]

+
# Var length input
+a, b, *c = map(int, input().split())
+print(a, type(a))
+print(b, type(b))
+print(c, type(c))
+
+

stdin

+
 10 20 30 40 50
+
+
+

stdout

+
10 <class 'int'>
+20 <class 'int'>
+[30, 40, 50] <class 'list'>
+
+
+

IN [9]

+
# one line input
+x, y, z = map(int, input().split())
+print(x, type(x))
+print(y, type(y))
+print(z, type(z))
+
+

stdin

+
 10 20 30
+
+
+

stdout

+
10 <class 'int'>
+20 <class 'int'>
+30 <class 'int'>
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/Cheat_sheet.pdf b/docs/Cheat_sheet.pdf new file mode 100644 index 0000000..6793b72 Binary files /dev/null and b/docs/Cheat_sheet.pdf differ diff --git a/docs/Condition_Statements.html b/docs/Condition_Statements.html new file mode 100644 index 0000000..f7926b3 --- /dev/null +++ b/docs/Condition_Statements.html @@ -0,0 +1,123 @@ + + + + + + + + Condition Statements + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Condition Statements

+ +

Condition statements or Control flow statements or Desicion Control Statements are statements that are used to control the flow or execution of a program. +The flow is controlled the values of few variables that decide the proceedings of a program.

+

The conditions statements have same basic structure in all programming languages. +The list of Control statements are: +1. if statement +2. if - else statements +3. if - elif - else statements +4. Nested if - else statements +5. Inline if - else statements

+

The condition given in the if statements need to result in allowed boolean values.
+1. For integral type: value!=0 is True and value=0 is False
+2. For list and tuple: length(value)>0 is True and length=0 is False
+(boolean as applicable)

+

1. if statement:

+

Executes the statements inside the block only if the condition is satisfied.

+

Syntax:

+
if condition:  
+    Statements
+
+

Note: Indentation in python indicates blocks.

+

IN [2]

+
# Example
+x = 14
+y = 18
+if y>x:
+    print(y)
+
+

stdout

+
18
+
+
+

IN [1]

+
# Example2
+x = int(input())
+if x:
+    print('not zero')
+
+# Input: -1
+
+

stdout

+
-1
+not zero
+
+
+

2. if - else statements:

+

Executes else when if condition fails
+Syntax:

+
if condition1:  
+    Statements  
+else:  
+    Statements
+
+

3. if - elif - else statements:

+

Checks for truth of elif statement when if statement fails. Chain of if-else
+Syntax:

+
if condition1:  
+    Statements  
+elif condition2:  
+    Statements  
+else:  
+    Statements
+
+

4. Nested if - else statements:

+

if else within another if else statement

+

Syntax:

+
if condition1:  
+    if condition2:  
+        Statements  
+    else:  
+        Statements  
+else:  
+    if condition3:  
+        Statements  
+    else:  
+        Statements  
+
+

5. Inline if - else statements:

+

One liner of if else statements

+

Syntax:

+
Statement1 if condition else Statement2
+
+
+ + + + + \ No newline at end of file diff --git a/docs/DS_Dictionaries.html b/docs/DS_Dictionaries.html new file mode 100644 index 0000000..66b9681 --- /dev/null +++ b/docs/DS_Dictionaries.html @@ -0,0 +1,412 @@ + + + + + + + + Data Structures or Derived data Types in Python: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Data Structures or Derived data Types in Python:

+ +

Storing multiple values of same or different types under a single name. +They are collection of data.

+
    +
  1. List
  2. +
  3. Tuple
  4. +
  5. String
  6. +
  7. Dictionary
  8. +
  9. Set
    +In this notebook, we’ll discuss indepth on Dictionaries
  10. +
+

Dictionary:

+

Dictionaries are unordered collection of data. +They are key-value mapping.
+Represented by Curly braces {}

+
dictionary : {1: 10, 2: 20, 3: 30, 4: 'Hello', 5: -2.0}
+
+

Defined by - key : value.
+Each key-value map is separated by comma (,)

+ + + + + + + + + + + + + + + + + + + + + +
Keys12345
Values1020304050
+

Defining a dictionary:

+
    +
  1. ’{ }’
  2. +
  3. dict()
  4. +
+

1. ‘{}’

+
dict1 = {1:10, 2:20, 3:30}
+
+

2. dict()

+

Syntax:

+
dict(iterable = None)
+
+

iterable: any data structures listed above given that elements are present as key value mapping.

+

IN [1]

+
d1 = {}
+type(d1)
+
+

IN [4]

+
l = [(1, 10), (2, 20), (3, 35)]
+d2 = dict(l)
+print(d2)
+type(d2)
+
+

stdout

+
{1: 10, 2: 20, 3: 35}
+
+
+

Methods or Functions in dictionaries:

+

There are various methods or functions that are used to work with dictionaries.
+1. len
+2. str
+3. clear
+4. copy
+5. fromkeys
+6. get
+8. items
+9. keys
+10. values
+11. update
+12. pop +13. popitem +10. setdefault

+

1. len:

+

Returns the length of the given iterable.

+

Syntax:

+
len(iterable)
+
+

IN [5]

+
d1 = {1: 12, 2: 23, 3: 34}
+len(d1)
+
+

2. str:

+

Returns the string format of the given dictionary.

+

Syntax:

+
str(dict)
+
+

IN [6]

+
d1 = {1: 12, 2: 23, 3: 34}
+str(d1)
+
+

3. clear:

+

Deletes the items in the dictionary.

+

Syntax:

+
dict.clear()
+
+

IN [7]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.clear()
+d1
+
+

4. copy:

+

Returns the shallow copy of the given dictionary.

+

Syntax:

+
dict.copy()
+
+

IN [8]

+
d1 = {1: 12, 2: 23, 3: 34}
+d2 = d1.copy()
+d2
+
+

5. fromkeys:

+

Returns a new dictionary form the given list of keys. By default the values are set to None.

+

Syntax:

+
dict.fromkeys(sep, val = None)
+
+

IN [12]

+
key = ['key1', 'key2', 'key3']
+d2 = dict.fromkeys(key)
+d2
+
+

IN [16]

+
key = ['key1', 'key2', 'key3']
+d2 = dict.fromkeys(key, 0)
+d2
+
+

6. get:

+

Returns the value of the given key if present else returns the default value given (None by Default).

+

Syntax:

+
dict.get(key, default = None)
+
+

IN [17]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.get(1)
+
+

IN [19]

+
d1 = {1: 12, 2: 23, 3: 34}
+print(d1.get(4))
+
+

stdout

+
None
+
+
+

IN [20]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.get(4, 0)
+
+

7. items:

+

Returns the list of key-value pairs in the dictionary.

+

Syntax:

+
dict.items()
+
+

IN [25]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.items()
+
+

8. keys:

+

Returns the list of keys present in the dictionary.

+

Syntax:

+
dict.keys()
+
+

IN [24]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.keys()
+
+

9. values:

+

Returns the list of values present on the dictionary.

+

Syntax:

+
dict.values()
+
+

IN [26]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.values()
+
+

10. update:

+

Adds the key-value pairs in second dictionary to the first.

+

Syntax:

+
dict.update(dict)
+
+

IN [27]

+
d1 = {1: 12, 2: 23, 3: 34}
+d2 = {4: 45, 5: 56}
+d1.update(d2)
+d1
+
+

11. pop:

+

Removes and returns the value of given key. If the key is absent, Error is raised if default is not given.

+

Syntax:

+
dict.pop(key, [default])
+
+

IN [28]

+
d1 = {1: 12, 2: 23, 3: 34}
+print(d1.pop(2))
+d1
+
+

stdout

+
23
+
+
+

IN [31]

+
d1 = {1: 12, 2: 23, 3: 34}
+print(d1.pop(4))
+d1
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 2, in <module>
+
+    print(d1.pop(4))
+
+KeyError: 4
+
+
+

IN [30]

+
d1 = {1: 12, 2: 23, 3: 34}
+print(d1.pop(4, 30))
+d1
+
+

stdout

+
30
+
+
+

12. popitem:

+

Removes and returns the last key-value pair of the dictionary.

+

Syntax:

+
dict.popitem()
+
+

IN [32]

+
d1 = {1: 12, 2: 23, 3: 34}
+print(d1.popitem())
+d1
+
+

stdout

+
(3, 34)
+
+
+

13. setdefault:

+

Sets the default value to key if the key is absent.

+

Syntax:

+
dict.setdefault(key, value)
+
+

IN [43]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1.setdefault(4, 45)
+d1
+
+

Accessing elements:

+

The values in the dictionary are accessed by key.

+

Syntax:

+
dictionary[key]
+
+

IN [33]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1[2]
+
+

IN [35]

+
d1 = {1: 12, 22: 23, 3: 34}
+d1[22]
+
+

IN [36]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1[4]
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 2, in <module>
+
+    d1[4]
+
+KeyError: 4
+
+
+

Adding or Modifying items:

+

Items can be added or modified by using keys.

+

If the key already exists, the value is replcaed by the new value. If not, new key-value pair is created

+

Syntax:

+
dictaionary[key] = value
+
+

IN [38]

+
d1 = {1: 12, 2: 23, 3: 34}
+d1[2] = 24 # modify
+d1[4] = 45 # add
+d1
+
+

Delete Elements:

+

Elements can be deleted by using the del keyword.

+

Syntax:

+
del dict[key]
+
+

IN [40]

+
d1 = {1: 12, 2: 23, 3: 34}
+del d1[2], d1[3]
+d1
+
+

Printing Items:

+

Use for loop to iterate through the dictionary.

+

IN [45]

+
d1 = {1: 12, 2: 23, 3: 34}
+for key, val in d1.items():
+    print(key, val)
+
+

stdout

+
1 12
+2 23
+3 34
+
+
+

Sorting a dictionary:

+

Dictionaries are sorted only by keys.

+

IN [51]

+
d1 = {1: 12, 2: 23, 3: 34}
+for i in sorted(d1.keys()):
+    print(i, d1[i])
+print()
+for i in sorted(d1):
+    print(i, d1[i])
+
+

stdout

+
1 12
+2 23
+3 34
+
+1 12
+2 23
+3 34
+
+
+

Nested Dictionaries:

+

Dictionaries inside a dictionary is nested dictionary.

+

IN [52]

+
d1 = {1: 12, 2: 23, 'd': {1: 12, 2: 23, 3: 34}}
+for i,j in d1.items():
+    print(i,j)
+
+

stdout

+
1 12
+2 23
+d {1: 12, 2: 23, 3: 34}
+
+
+

Dictionaries and list Comprehension:

+

Dictionaries can be defined by comprehensions.

+

Syntax:

+
dict = {key: value (loops)}
+
+

IN [53]

+
d2 = {x: x**2 for x in range(10)}
+d2
+
+

Dictionaries for switch case:

+

Dictionaries can be used as switch cases.

+

IN [55]

+
switch = {1: 'One',
+          2: 'Two', 
+          3: 'Three'}
+switch[1]
+
+
+ + + + + \ No newline at end of file diff --git a/docs/DS_Lists.html b/docs/DS_Lists.html new file mode 100644 index 0000000..0c9f647 --- /dev/null +++ b/docs/DS_Lists.html @@ -0,0 +1,937 @@ + + + + + + + + Data Structures or Derived data Types in Python: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Data Structures or Derived data Types in Python:

+ +

Storing multiple values of same or different types under a single name. + They are collection of data.

+
    +
  1. List
  2. +
  3. Tuple
  4. +
  5. String
  6. +
  7. Dictionary
  8. +
  9. Set
    + In this notebook, we’ll discuss indepth on Lists
  10. +
+

Lists:

+

Lists are ordered collection of data. + Represented by square brackets ‘[ ]’

+
list : [10, 20, 30, 'Hello', -2.0]
+
+

Each value in the list is called a element
+ order of elements: index of element
+ Index - may be positive or negative

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Order (element)FirstSecondThirdLast
Positive Index012n-1
Negative Index-n-n+1-n+2-1
+

Defining a list:

+
    +
  1. ’[ ]’
  2. +
  3. list()
  4. +
+

1. ‘[ ]’

+
l = [10, 20, 30]
+
+

2. list()

+

Syntax:

+
list(iterable = None)
+
+

iterable: any data structures listed above

+

IN [1]

+
l = [10, 'Hello', -3.9]
+type(l)
+
+

IN [2]

+
list1 = list()
+list1
+
+

IN [3]

+
list2 = list(1)
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 1, in <module>
+
+    list2 = list(1)
+
+TypeError: 'int' object is not iterable
+
+
+

Getting list as input:

+
list1 = list(input())  
+list1 = list(input().split())
+
+

To know more on split(), find it in Data Structures - Strings

+

IN [4]

+
list1 = list(input())
+list1
+
+# Input: Hello
+
+

stdin

+
 Hello
+
+
+

IN [5]

+
list2 = list(input().split())
+list2
+# Input: 10 20 30 40.0
+
+

stdin

+
 10 20 30 40.0
+
+
+

IN [7]

+
list3 = list(input().split())
+list3
+# Input: Hello Python
+
+

stdin

+
 Hello Python
+
+
+

Methods or Functions in list:

+

There are various methods or functions that are used to work on lists.
+ 1. append
+ 2. insert
+ 3. pop
+ 4. map
+ 5. filter
+ 6. sort
+ 7. sorted
+ 8. extend
+ 9. index
+ 10. remove
+ 11. reduce
+ 12. reverse
+ 13. len
+ 14. count
+ 15. sum
+ 16. max
+ 17. min
+ 18. enumerate

+

1. append:

+

Adds the given element to the end of the list.
+ Syntax:

+
list.append(element)
+
+

IN [12]

+
# Example
+l = []
+n = 1
+l.append(10)
+l.append(15)
+l.append('Hello')
+l.append(n)
+print(l)
+
+

stdout

+
[10, 15, 'Hello', 1]
+
+
+

2. insert:

+

Inserts the element at the index specified
+ Syntax:

+
list.insert(index, element)
+
+

IN [1]

+
# Example
+list1 = [10, 15, 25, 30]
+n = 35
+list1.insert(2, 20)
+list1.insert(-1, n)
+list1
+
+

3. pop:

+

Removes and returns the element from the index specified. Default is last element

+

Syntax:

+
list.pop(index = -1)
+
+

IN [18]

+
list2 = [10, 100, 1000, 'Hi']
+print(list2.pop())
+print(list2)
+print(list2.pop(1))
+list2
+
+

stdout

+
Hi
+[10, 100, 1000]
+100
+
+
+

4. map:

+

Applies the given function to every element in a list or iterable.

+

Syntax:

+
map(function, iterable)
+
+

IN [1]

+
def sample_fn(x):
+    return x+2
+l = [1, 2, 3, 4]
+l = list(map(sample_fn, l))
+l
+
+

Getting a list of integers or float as input:

+

Use map function to map int function to each value

+

IN [4]

+
list1 = list(map(int, input().split()))
+print(type(list1[0]))
+list1
+
+# Input: 10 20 30 40
+
+

stdin

+
 10 20 30 40
+
+
+

stdout

+
<class 'int'>
+
+
+

5. filter:

+

Filters out the elements that match the given condition

+

Syntax:

+
filter(condition, iterable)
+
+

The condition should be given as a function definition which can be mapped to each variable.

+

IN [5]

+
l = [1, -1, 0, 3, -10, 100]
+list2 = list(filter(lambda x: x>0, l)) # A Lambda function used for condition
+print(list2)
+
+

stdout

+
[1, 3, 100]
+
+
+

6. sort:

+

Sorts the list as per the given condition

+

Syntax:

+
list.sort(key = None, reverse = False)
+
+

IN [8]

+
l = [10, 60, 0, 40, -100]
+l.sort() # Ascending order
+print(l)
+l.sort(reverse = True) # Descending Order
+print(l)
+
+

stdout

+
[-100, 0, 10, 40, 60]
+[60, 40, 10, 0, -100]
+
+
+

IN [14]

+
l1 = ['Hi', 'Python', 'how', 'String', 'Data', 'Sorting Strings']
+l1.sort() #lexicographic sorting (as per unicode values)
+print(l1)
+l1.sort(key = len, reverse = True)
+print(l1)
+
+

stdout

+
['Data', 'Hi', 'Python', 'Sorting Strings', 'String', 'how']
+['Sorting Strings', 'Python', 'String', 'Data', 'how', 'Hi']
+
+
+

7. sorted:

+

It is also function used to sort. Difference is that the sorted list should be reassigned to a variable.

+

Syntax:

+
sorted(iterable, key = None, reverse = False)
+
+

IN [3]

+
l1 = [10, 20, 50, 0, -10, -1, 100]
+l2 = sorted(l1)
+print(l1)
+l2
+
+

stdout

+
[10, 20, 50, 0, -10, -1, 100]
+
+
+

8. extend:

+

Extends the given list using the elements of iterable, i.e. appends the elements of iterable to the given + list

+

Syntax:

+
list.extend(iterable)
+
+

IN [1]

+
l = [10, 20, 30, 40]
+l.extend([50, 60, 70])
+l
+
+

IN [2]

+
l1 = ['H','e', 'l', 'l', 'o']
+l1.extend('Welcome')
+l1
+
+

9. index:

+

Returns the index of the element in the list. If multiple elements exist, it gives the index of first + occurrence. If the element is not in the list, it raises an error

+

Syntax:

+
list.index(element)
+
+

IN [5]

+
l = [10, 20, 30, 40, 10]
+l.index(10)
+
+

10. remove:

+

Removes the first occurence of the element if present. Raises error when element not present

+

Syntax:

+
list.remove(value)
+
+

IN [6]

+
l = [10, 20, 30, 40]
+l.remove(20)
+l
+
+

IN [7]

+
l.remove(20) # Removing element that is not present
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 1, in <module>
+
+    l.remove(20) # Removing element that is not present
+
+NameError: name 'l' is not defined
+
+
+

11. reduce:

+

Sequentially applies the elements in the list to a function to give the final value. To use this we need to + call functools module. In depth study of modules will be dealt later

+

Syntax:

+
reduce(function, list)
+
+

IN [8]

+
from functools import reduce
+
+def add(x, y):
+    return x+y
+
+l = [10, 20, 30, 40]
+c = reduce(add, l)
+c
+
+

Explanation:

+

Step 1: + applies 10 and 20 to the function. result = 30

+

Step 2: + applies the result and next element (30). result = 60

+

Step 3: + applies the result and next element (40). result = 100

+

List end is reached. so the result 100 is returned

+

12. reverse:

+

Used to reverse the list.

+

Syntax:

+
list.reverse()
+
+

IN [10]

+
list1 = [10, 20, 30, 50, 60]
+list1.reverse()
+list1
+
+

13. len:

+

Returns the length of the given iterable

+

Syntax:

+
len(iterable)
+
+

IN [11]

+
list2 = [10, 20, 30, -1, 123]
+len(list2)
+
+

14. count:

+

Returns the count of the element specified

+

Syntax:

+
list.count(element)
+
+

IN [14]

+
l = [10, 20, 30, 10, 20, 25, 20, 50]
+print(l.count(20))
+l.count(10)
+
+

stdout

+
3
+
+
+

15. sum:

+

returns the sum elements in the list or tuple.

+

Syntax:

+
sum(list, start = 0)
+
+

IN [1]

+
l = [10, -10, 20, -30, 40]
+sum(l)
+
+

IN [2]

+
l = ['Hello', 'World'] # Non Numeric data raise error.
+sum(l)
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 2, in <module>
+
+    sum(l)
+
+TypeError: unsupported operand type(s) for +: 'int' and 'str'
+
+
+

16. max:

+

Returns the maximum value in the list.

+

Syntax:

+
max(list, key = None)
+
+

IN [5]

+
l = [10, 15, 50, 21, -7]
+max(l)
+
+

IN [9]

+
l = [10, 15, 50, 21, -7, 7]
+max(l, key = lambda x: x % 5) # Maximum reminder when divided by 5
+
+

17. min:

+

Returns minimum value in the iterable

+

Syntax:

+
min(iterable, key = None)
+
+

IN [11]

+
l = [10, 15, 50, 21, -7]
+min(l)
+
+

18. enumerate:

+

Returns the enumerate object for given list. An enumerate object is an iterable which contains ordered pair + of the form (index, value)

+

Syntax:

+
enumerate(iterable, start = 0)
+
+

IN [14]

+
l = [10, 20, 'Hello', 'a', -1]
+list(enumerate(l))
+
+

Accessing Elements in a list:

+

Elements of a list can be accessed using index.

+

Example:
+ Consider a list, l = [10, 20, 30, 40, 50]. Length = 5

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Element1020304050
Position12345
Positive Index01234
Negative Index-5-4-3-2-1
+

Calling $i^{th}$ element:
+ positive index: l[i-1]
+ negative index: l[i - 1 - length]

+

IN [1]

+
l = [10, 50, 20, 30, -2]
+n = len(l) # length
+print(n-1, l[n-1]) # Last Element Positive index
+print(l[-1]) # Last Element negative index
+print(l[2]) # third element
+
+

stdout

+
4 -2
+-2
+20
+
+
+

IN [15]

+
l = [10, 50, 20, 30, -2]
+for index, element in enumerate(l):
+    print(index, element)
+
+

stdout

+
0 10
+1 50
+2 20
+3 30
+4 -2
+
+
+

Slicing operator:

+

Used to get / set a sublist of a list. Denoted by '[]'

+

Syntax:

+
list_name[start = 0 : stop = length : step = 1]
+
+

IN [19]

+
# Getting sublist in forward direction
+l = [10, 50, 20, 30, -2]
+print(l[1:-1])
+print(l[1::2])
+print(l[::2])
+
+

stdout

+
[50, 20, 30]
+[50, 30]
+[10, 20, -2]
+
+
+

IN [24]

+
# Getting Sublist in reverse:
+l = [10, 50, 20, 30, -2]
+print(l[4:0:-1])
+print(l[::-1]) # reverse of the list
+print(l[::-2]) # reverse list every alternate term
+
+

stdout

+
[-2, 30, 20, 50]
+[-2, 30, 20, 50, 10]
+[-2, 20, 10]
+
+
+

Printing the elements in a list:

+
    +
  1. Using loops
  2. +
  3. Using Variable length argument ( * )
  4. +
+

1. Looping:

+

Use for or while loop to access element or list.

+

2. Using * :

+

Using * will convert the elements of the list into arguements of print method

+

IN [2]

+
# for loop to get index
+l = [10, 20, 30, 40, 50]
+for i in range(len(l)):
+    print(l[i], end= ' ')
+
+

stdout

+
10 20 30 40 50 
+
+

IN [3]

+
# for loop to get elements
+l = [10, 20, 30, 40, 50]
+for i in l:
+    print(i, end = ' ')
+
+

stdout

+
10 20 30 40 50 
+
+

IN [5]

+
# while loop to get index
+l = [10, 20, 30, 40, 50]
+i = 0
+while i<len(l):
+    print(l[i], end= ' ')
+    i += 1
+
+

stdout

+
10 20 30 40 50 
+
+

IN [6]

+
# Using *
+l = [10, 20, 30, 40, 50]
+print(*l)
+
+

stdout

+
10 20 30 40 50
+
+
+

List Comprehension:

+

It follows the form of the mathematical set-builder notation unlike the use of map and filter functions. It + is used to create lists from either an existing like or a completely new list.

+

Set builder form: + $\{x: x ~\rm{\epsilon~ list}\}$
+ Example:

+
list1 = [expression (loops)]
+
+

IN [9]

+
# map vs comprehension
+l = [10, 20, 30, 40, 50]
+s = [i**2 for i in l] # squares of elements in list l using comprehension
+sq = list(map(lambda x: x**2, l)) # Using map
+print(*s)
+print(*sq)
+
+

stdout

+
100 400 900 1600 2500
+100 400 900 1600 2500
+
+
+

IN [13]

+
# Equivalent of above comprehension
+l = [10, 20, 30, 40, 50]
+s = list()
+for i in l:
+    s.append(i ** 2)
+print(*s)
+
+

stdout

+
100 400 900 1600 2500
+
+
+

IN [10]

+
# filter vs comprehension
+l = [10, 20, 30, 40, 50]
+mul_t = [i for i in l if i % 20 == 0] # Multiples o twenty in l Using Comprehension
+mul_tc = list(filter(lambda x: x % 20 == 0, l )) #Using filter
+print(*mul_t)
+print(*mul_tc)
+
+

stdout

+
20 40
+20 40
+
+
+

IN [14]

+
# Equivalent of above comprehension
+l = [10, 20, 30, 40, 50]
+mul = list()
+for i in l:
+    if i % 20 == 0: mul.append(i)
+print(*mul)
+
+

stdout

+
20 40
+
+
+

List Aliasing:

+

Aliasing a list variable with another name. Referring a single list by multiple names.
+ Syntax:

+
new_name = old_name
+
+

IN [15]

+
a = [10, 20, 0]
+b = a # aliasing list a
+b
+
+

List Copying or Cloning:

+

Create a new instance of list with same value. It is used to copy a list to a new variable by new memory + allocation.

+

Types:

+
    +
  1. Shallow Copy
  2. +
  3. Deep copy
  4. +
+

Methods:

+
    +
  1. copy method
  2. +
  3. slicing operator
  4. +
  5. list method
  6. +
  7. copy module
  8. +
+

1. Copy method:

+

Creates a shallow copy of variable

+

Syntax:

+
new_list = list.copy(list_name)
+
+

IN [8]

+
l = [10, 20, 30, 40]
+list1 = l.copy()
+list1
+
+

2. slicing operator:

+

Another method for shallow copy

+

Syntax:

+
new_list = old_list[:]
+
+

IN [16]

+
l = [10, 20, 30]
+list2 = l[:]
+list2
+
+

3. list function:

+

Create a new instance using list function. It also results in shallow copy

+

Syntax:

+
list_new = list(old_list)
+
+

IN [17]

+
l = [10, 20, 30]
+m = list(l)
+m
+
+

4. Copy module:

+

Copy module can be used to copy list to new variable

+

Functions: + 1. copy + 2. deepcopy

+

1. copy:

+

creates shallow copy

+

Syntax:

+
new_list = copy(list_name)
+
+

2. deepcopy:

+

Creates a deep copy

+

Syntax:

+
new_list = deepcopy(list_name)
+
+

IN [18]

+
import copy
+
+l = [10, 20, 30]
+m = copy.copy(l)
+s = copy.deepcopy(l)
+print(m)
+s
+
+

stdout

+
[10, 20, 30]
+
+
+

Multi-dimensional lists or matrices:

+

Lists in a list is called a multidimensional list or nested lists. They are generally used to work with + matrices.

+

Example:

+
list = [[10, 20, 30], [40, 50, 60]] # - Two dimensional list
+
+

Accessing elements using index:

+

Syntax:

+
list_name[outermost list index][inner list index]...
+
+

IN [25]

+
m = [[10, 20, 30], [40, 50, 60]] # two dimensional
+print(m[0]) # first element in outermost list
+print(m[0][0]) # first element in first inner list
+
+

stdout

+
[10, 20, 30]
+10
+
+
+

IN [31]

+
l = [ [[10, 20], [30]], 
+     [[40, 50,], [60]] ] # three dimensional
+print(l[0]) # first element in outermost list
+print(l[0][0]) # first element in first inner list
+print(l[0][0][0]) # first element in first innermost list in first inner list
+
+

stdout

+
[[10, 20], [30]]
+[10, 20]
+10
+
+
+

Matrix:

+

A rectangular array of elements. Two dimensional lists or tuples are used to work with matrices.

+

Each row of matrix is stored as a list

+

Example:

+
matrix = [[10, 20, 30], [40, 50, 60]]
+
+

Matrix input:

+

Matrix can be taken as input using loops or list comprehension.

+

IN [2]

+
# Using loops and append function:
+matrix1 = list()
+n = int(input()) # no. of rows
+for i in range(n):
+    matrix1.append(list(map(int, input().split()))) # a row of integer input
+matrix1
+# Input: 3
+# 10 2 -3
+# -2 1 0
+# 3 9 11
+
+

stdin

+
 3
+ 10 2 -3
+ -2 1 0
+ 3 9 11
+
+
+

IN [3]

+
# Using list comprehension:
+m = int(input()) # no. of rows
+matrix2 = [ list(map(int, input().split())) for i in range(m)] # a matrix input
+matrix2
+# Input: 3
+# 10 2 -3
+# -2 1 0
+# 3 9 11
+
+

stdin

+
 3
+ 10 2 -3
+ -2 1 0
+ 3 9 11
+
+
+

Output:

+

Output is printed using for loop

+

IN [4]

+
# Using iterable:
+matrix3 = [[1, 2],[4, 3]] # A 2x2 matrix 
+for i in matrix3:
+    print(*i)
+
+

stdout

+
1 2
+4 3
+
+
+

IN [5]

+
# Using range:
+matrix3 = [[1, 2],[4, 3]] # A 2x2 matrix 
+for i in range(len(matrix3)):
+    print(*matrix3[i])
+
+

stdout

+
1 2
+4 3
+
+
+

IN [6]

+
# Using nested loop:
+matrix3 = [[1, 2],[4, 3]] # A 2x2 matrix 
+for i in range(len(matrix3)):
+    for j in range(len(matrix3[0])):
+        print(matrix3[i][j], end=' ')
+    print()
+
+

stdout

+
1 2 
+4 3 
+
+
+

Stack:

+

A data type where elements are arranged such that the elements can only be added to and removed from the + last.
+ It follows the principle FILO - First In Last Out

+

Methods used: append() and pop()

+

Queue

+

A data type where elements are arranged such that the elements can only be added to the last and removed from + the first.
+ It follows the principle FIFO - First In First Out

+

Methods Used: append() and pop(0)

+

Mutability:

+

It is the ability to change the value of an element in a Data structure during execution.

+

1. Mutables:

+
    +
  1. List
  2. +
  3. Dictionary
  4. +
  5. Sets
  6. +
+

2. Immutable:

+
    +
  1. Tuple
  2. +
  3. String
  4. +
+

Working with lists:

+
    +
  1. Concatenation
  2. +
  3. Appending
  4. +
  5. Multiplication
  6. +
+

1. Concatenation:

+

Two lists can be concatenated by using ‘+’ operator.

+

IN [2]

+
l1 = ['list']
+l2 = ['Concatenation']
+l1 + l2 # Concatenation
+
+

2. Appending:

+

A list can be appended to string using ‘+=’ operator or by reassignment.

+

IN [3]

+
l3 = ['Let']
+ch = ['s']
+l3 += ch # str3 = str3 + ch
+l3
+
+

3. List Multiplication:

+

List multiplication results a list with repitition. It can be done using ‘ * ‘ operator.

+

IN [5]

+
l4 = ['Namaste ', 'Hello']
+l4*5
+
+

List Comparison:

+

Python allows usage of relational operators on List.

+

Python compares two lists using the elements present in them. Whenever a greater element is encounter thr + boolean value is returned.

+
+ + + + + \ No newline at end of file diff --git a/docs/DS_Sets.html b/docs/DS_Sets.html new file mode 100644 index 0000000..a462e1d --- /dev/null +++ b/docs/DS_Sets.html @@ -0,0 +1,331 @@ + + + + + + + + Data Structures or Derived data Types in Python: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Data Structures or Derived data Types in Python:

+ +

Storing multiple values of same or different types under a single name. +They are collection of data.

+
    +
  1. List
  2. +
  3. Tuple
  4. +
  5. String
  6. +
  7. Dictionary
  8. +
  9. Set
    +In this notebook, we’ll discuss indepth on Sets
  10. +
+

Sets:

+

Sets are unordered collection of unique data. +Enclosed by Curly braces {}

+
set: {10, 20.2, 30.0}
+
+

Each value in the set is called a element
+Since set is unordered collection, it cannot be indexed. The elements are randomly stored.

+

Defining a set:

+

set() method

+

Syntax:

+
set(iterable = None)
+
+

iterable: any data structures listed above

+

By default the {} map to a dictionary. So empty curly braces cannot be used.

+

IN [2]

+
l = [10, 20, 30]
+s = set(l)
+s
+
+

IN [5]

+
s = {10, 20, 30, 10, 30}
+s
+
+

Getting set as input:

+
s1 = set(input())  
+s2 = set(input().split())
+
+

Methods or Functions in sets:

+

There are various methods or functions that are used to work on sets.
+1. add
+2. update
+3. discard
+4. pop
+5. clear
+6. len
+7. issubset
+8. issuperset
+9. union
+10. intersection
+11. intersection_update
+12. difference
+13. symmetric_difference
+14. copy
+15. isdisjoint
+16. max
+17. min
+18. enumerate +19. sum +20. sorted

+

1. add:

+

Adds an element to the end of the set.

+

Syntax: set.add(element)

+

IN [6]

+
set1 = {10, 20, 30}
+set1.add(40)
+set1
+
+

2. update:

+

Adds elements in another set to given set

+

Syntax: set.update(set)

+

IN [8]

+
set1 = {10, 20, 30}
+set2 = {10, 25, 40}
+set1.update(set2)
+set1
+
+

3. discard:

+

Discards the given element in the set.

+

Syntax: set.discard(element)

+

IN [9]

+
set1 = {10, 20, 30}
+set1.discard(20)
+set1
+
+

4. pop:

+

Removes and returns a random element from set.

+

Syntax: set.pop()

+

IN [12]

+
set1 = {10, 20, 30}
+set1.pop()
+
+

5. clear:

+

Empties the set.

+

Syntax: set.clear()

+

IN [13]

+
set1 = {10, 20, 30}
+set1.clear()
+set1
+
+

6. len

+

Returns the length of the set

+

Syntax: len(set)

+

7. issubset:

+

Checks if a set subset of another.

+

Syntax: set.issubset(set)
+Or set1 <= set2

+

IN [14]

+
set1 = {10, 20, 30}
+set2 = {10, 20}
+set2.issubset(set1)
+
+

8. issuperset:

+

Checks if the set superset of another.

+

Syntax: set.issuperset(set)
+Or set1 >= set2

+

IN [15]

+
set1 = {10, 20, 30}
+set2 = {10, 20, 30, 35}
+set2.issuperset(set1) # set1.issubset(set2)
+
+

9. union:

+

Returns the union of 2 sets

+

Syntax: set.union(set)
+Or set1|set2

+

IN [16]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1.union(set2)
+
+

IN [18]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1|set2
+
+

10. intersection:

+

Returns the intersection of 2 sets

+

Syntax: set.intersection(set2)
+Or set1 & set2

+

IN [17]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1.intersection(set2)
+
+

IN [22]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1 & set2
+
+

11. intersection_update:

+

Updates the set with intersection of given set.

+

Syntax: set.intersection_update(set)
+Or set1 &= set2

+

IN [24]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1.intersection_update(set2)
+set1
+
+

IN [25]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1 &= set2
+set1
+
+

12. difference:

+

Returns the set difference of given set

+

Syntax: set1-set2
+Or set1 - set2

+

IN [26]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1.difference(set2)
+
+

13. Symmetric Difference:

+

Returns the symmetric difference of two sets.

+

Syntax: set.symmetric_difference(set) +Or set1 ^ set2

+

IN [27]

+
set1 = {10, 20, 30}
+set2 = {12, 22, 30}
+set1.symmetric_difference(set2)
+
+

14. copy:

+

Copies a set

+

Syntax: set.copy()

+

IN [28]

+
set1 = {10, 20, 30}
+set2 = set1.copy()
+set2
+
+

15. isdisjoint:

+

Checks if the given sets are mutually exclusive.

+

Syntax: set.isdisjoint(set)

+

IN [29]

+
set1 = {10, 20, 30}
+set2 = {1, 22, -37}
+set1.isdisjoint(set2)
+
+

IN [1]

+
l = [10, -10, 20, -30, 40]
+sum(l)
+
+

16. max:

+

Returns the maximum value in the set.

+

Syntax: max(set, key = None)

+

IN [35]

+
l = {10, 15, 50, 21, -7}
+max(l)
+
+

IN [36]

+
l = {10, 15, 50, 21, -7, 7}
+max(l, key = lambda x: x % 5) # Maximum reminder when divided by 5
+
+

17. min:

+

Returns minimum value in the iterable

+

Syntax: min(iterable, key = None)

+

IN [37]

+
l = {10, 15, 50, 21, -7}
+min(l)
+
+

18. enumerate:

+

Returns the enumerate object for given set. An enumerate object is an iterable which contains ordered pair of the form (index, value)

+

Syntax: enumerate(iterable, start = 0)

+

IN [39]

+
l = {10, 20, 'Hello', 'a', -1}
+list(enumerate(l))
+
+

19. sum:

+

returns the sum elements in the set.

+

Syntax: sum(set, start = 0)

+

20. sorted:

+

It is a function used to sort.

+

Syntax: sorted(iterable, key = None, reverse = False)

+

Printing the elements in a set:

+
    +
  1. Using loops
  2. +
  3. Using Variable length argument ( * )
  4. +
+

1. Looping:

+

Use for loop to access element.

+

2. Using * :

+

Using * will convert the elements of into arguements of print method

+

IN [30]

+
set1 = {10, 20, 30}
+for i in set1:
+    print(i)
+
+

stdout

+
10
+20
+30
+
+
+

IN [31]

+
set1 = {10, 20, 30}
+print(*set1)
+
+

stdout

+
10 20 30
+
+
+

Comprehensions:

+

IN [32]

+
set1 = set(i+1 for i in range(0, 10))
+set1
+
+

all and any:

+

any checks if any of the element in an iterable is true.

+

all checks if all the element on an iterable is True

+

IN [33]

+
l = [10, 20, 30, 0]
+print(any(l))
+print(all(l))
+
+

stdout

+
True
+False
+
+
+

IN [34]

+
set1 = {10, 20, 30, -1}
+print(any(set1))
+print(all(set1))
+
+

stdout

+
True
+True
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/DS_Strings.html b/docs/DS_Strings.html new file mode 100644 index 0000000..f991537 --- /dev/null +++ b/docs/DS_Strings.html @@ -0,0 +1,699 @@ + + + + + + + + Data Structures or Derived data Types in Python: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Data Structures or Derived data Types in Python:

+ +

Storing multiple values of same or different types under a single name. +They are collection of data.

+
    +
  1. List
  2. +
  3. Tuple
  4. +
  5. String
  6. +
  7. Dictionary
  8. +
  9. Set
    +In this notebook, we’ll discuss indepth on Strings
  10. +
+

Strings:

+

Strings are ordered collection or an array of characters. +Represented by quotes either ‘ ‘ or ” “.
+They are generally immutable. This means individual elements can’t be changed.

+
Example: 'Hello', "Python"
+
+

order of elements: index of element
+Index - may be positive or negative

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Order (element)FirstSecondThirdLast
Positive Index012n-1
Negative Index-n-n+1-n+2-1
+

Defining a String:

+
    +
  1. ’‘ or “”
  2. +
  3. str()
  4. +
+

1. Quotes:

+
str = 'String'
+
+

2. str()

+

Syntax:

+
str(value = None)
+
+

IN [2]

+
str1 = 'Hello'
+type(str1)
+
+

IN [3]

+
s = str([10, 20])
+print(s)
+type(s)
+
+

stdout

+
[10, 20]
+
+
+

String Input:

+

All the values that are taken using input() method as strings.

+

IN [8]

+
s1 = input()
+type(s1)
+# Input: String
+
+

stdin

+
 String
+
+
+

Working with Strings:

+
    +
  1. Concatenation
  2. +
  3. Appending
  4. +
  5. Multiplication
  6. +
+

1. Concatenation:

+

Two strings can be concatenated by using + operator.

+

IN [11]

+
str1 = 'String '
+str2 = 'Concatenation'
+str1+str2 # Concatenation
+
+

2. Appending:

+

A character can be appended to string using += operator or by reassignment.

+

IN [14]

+
str3 = 'Let'
+ch = 's'
+str3 += ch # str3 = str3 + ch
+str3
+
+

3. String Multiplication:

+

String multiplication results a string with repitition. It can be done using * operator.

+

IN [16]

+
str4 = 'Namaste '
+str4*4
+
+

Built-in String Methods:

+

There are various methods to work with strings. But Unlike lists, string methods don’t change strings as ther are immutable. Hence the returned value should always be reassigned.

+

Methods: +1. capitalize +2. upper +3. lower +4. Center +5. swapcase +6. find +7. rfind +8. index +9. startswith +10. endswith +11. isalnum +12. isalpha +13. isdigit +14. strip +15. split +16. join +17. replace +18. zfill +19. enumerate +20. len +21. isupper +22. islower +23. lstrip +24. rstrip +25. partition +26. ljust +27. rjust +28. sorted

+

1. capitalize:

+

Capitalize the string. More specifically, first letter of the string in upper case and rest in lower case.

+

Syntax:

+
str.capitalize()
+
+

IN [18]

+
s1 = 'hello'
+s1 = s1.capitalize()
+s1
+
+

2. upper:

+

Converts the string to upper case

+

Syntax:

+
str.upper()
+
+

IN [19]

+
s1 = 'hello'
+s1 = s1.upper()
+s1
+
+

3. lower:

+

Converts the string to lowercase

+

Syntax:

+
str.lower()
+
+

IN [20]

+
s1 = 'HI'
+s1.lower()
+
+

4. center:

+

Returns original string to center of given width. The empty places are filled using fillchar

+

Syntax:

+
str.center(width, fillchar)
+
+

IN [22]

+
s1 = 'hii'
+s1 = s1.center(5, '*')
+s1
+
+

IN [23]

+
s2 = 'Well'
+s2 = s2.center(10, '-')
+s2
+
+

5. swapcase:

+

Swaps the case of string to lower if in uppercase, to upper in lowercase

+

Syntax:

+
str.swapcase()
+
+

IN [24]

+
s1 = 'PyThon'
+s1.swapcase()
+
+

6. find:

+

Returns the index of start of substring if present in string else -1.

+

Syntax:

+
str.find(substring, start = 0, end = length)
+
+

IN [32]

+
s1 = 'Python'
+s1.find('Py')
+
+

7. rfind:

+

Returns index of start of last occurence substring if present in string else -1

+

Syntax:

+
str.rfind(substring, start = 0, end = length)
+
+

IN [34]

+
s1 = 'Hello Welcome'
+s1.rfind('el')
+
+

8. index:

+

Returns the index of substring given. Same as find but raises error if absent.

+

Syntax:

+
str.index(substring, start = 0, end = length)
+
+

IN [37]

+
s1 = 'Python'
+s1.index('Py')
+
+

9. startswith:

+

Checks if the given string starts with given Prefix.

+

Syntax:

+
str.startswith(prefix, start = 0, end = length)
+
+

IN [6]

+
str1 = 'preprocessing'
+str1.startswith('pre')
+
+

10. endswith:

+

Checks if the given string ends with the given suffix.

+

Syntax:

+
str.endswith(suffix, start = 0, end = length)
+
+

IN [7]

+
str1 = 'preprocessor'
+str1.endswith('or')
+
+

11. isalnum:

+

Checks if the given string is alpha-numeric, i.e., contains only alphabets or numbers.

+

Syntax:

+
str.isalnum()
+
+

IN [8]

+
s2 = '$hello_'
+s2.isalnum()
+
+

IN [11]

+
s3 = 'dev23'
+s3.isalnum()
+
+

12. isalpha:

+

Checks if the given string is alphabetic, i.e., contains only alphabets.

+

Syntax:

+
str.isalpha()
+
+

IN [12]

+
s3 = 'dev23'
+s3.isalpha()
+
+

IN [13]

+
s4 = 'python'
+s4.isalpha()
+
+

13. isdigit:

+

Checks if the given string is numeric, i.e., contains only numbers.

+

Syntax:

+
str.isdigit()
+
+

IN [14]

+
s3 = 'dev23'
+s3.isdigit()
+
+

IN [15]

+
s5 = '123'
+s5.isdigit()
+
+

14. strip:

+

Removes the leading and trailing whitespaces by default, if any. If chars is given (string only), it removes only the characters in it.

+

Syntax:

+
str.strip(chars = None)
+
+

IN [16]

+
str1 = ' Hello '
+str1.strip()
+
+

IN [21]

+
str2 = 'HhelloH '
+str2.strip('H ')
+
+

15. split:

+

Return a list of the words in the string, using sep as the delimiter. maxsplit gives the Maximum no. of splits to be done. The remaining string returned as last element. By default whitespaces, line feed and carriage returns are taken as delimiters.

+

Syntax:

+
str.split(/, sep = None, maxsplit = -1)
+
+

IN [22]

+
str1 = 'Hello\n World\r'
+str1.split()
+
+

IN [27]

+
str2 = 'Hello-World '
+str2.split('-')
+
+

IN [32]

+
str1 = 'Hello\n World\r'
+str1.split(maxsplit = 1) # Limiting no. of split
+
+

16. join:

+

Returns a concatenated string of iterable (containing only strings) with char (string) as delimiter.

+

Syntax:

+
char.join(iterable)
+
+

IN [29]

+
list1 = ['Hello', 'World']
+"".join(list1)
+
+

IN [30]

+
list1 = ['Hello', 'World']
+" ".join(list1)
+
+

IN [31]

+
list1 = ['Hello', 'World']
+"-".join(list1)
+
+

17. replace:

+

Returns a copy of a string with given substring replaced by old substring. count is the max no. of occurences to be replaced, all be default.

+

Syntax:

+
str.replace(old_string, new_string, count = -1)
+
+

IN [35]

+
str1 = 'Hello World'
+str1.replace('l','L')
+
+

18. zfill:

+

Pads zeroes (0) to the start of the numeric string to fill the given width if width > length of string.

+

Syntax:

+
str.zfill(width)
+
+

IN [36]

+
num = '123'
+num.zfill(2)
+
+

IN [37]

+
num = '123'
+num.zfill(5)
+
+

19. enumerate:

+

Returns the enumeration object of given string.

+

Syntax:

+
enumerate(str)
+
+

IN [44]

+
str1 = 'Hello'
+print('(Index, Value)')
+print(*enumerate(str1), sep='\n') # enumeration object
+
+

stdout

+
(Index, Value)
+(0, 'H')
+(1, 'e')
+(2, 'l')
+(3, 'l')
+(4, 'o')
+
+
+

20. len:

+

Returns the length o given string

+

Syntax:

+
len(str)
+
+

IN [42]

+
str1 = 'Prabhu'
+len(str1)
+
+

21. isupper:

+

Checks if the given string is in uppercase.

+

Syntax:

+
str.isupper()
+
+

IN [45]

+
str1 = 'HYMN'
+str1.isupper()
+
+

22. islower:

+

Checks if the given string is in lowercase.

+

Syntax:

+
str.islower()
+
+

IN [46]

+
str2 = 'welcome'
+str2.islower()
+
+

23. lstrip:

+

Removes the leading whitespaces by default, if any. If chars is given (string only), it removes only the characters in it.

+

Syntax:

+
str.lstrip(chars = None)
+
+

IN [47]

+
str1 = ' Hello '
+str1.lstrip()
+
+

24. rstrip:

+

Removes the trailing whitespaces by default, if any. If chars is given (string only), it removes only the characters in it.

+

Syntax:

+
str.rstrip(chars = None)
+
+

IN [48]

+
str1 = ' Hello '
+str1.rstrip()
+
+

25. partition:

+

Partition the string into three parts using the given separator.

+

If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

+

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

+

Syntax:

+
str.partition(sep)
+
+

IN [51]

+
str2 = 'Hello-World'
+str2.partition('-')
+
+

IN [54]

+
str2 = 'Hello-World'
+str2.partition('a')
+
+

26. ljust:

+

Pads given char (default - space) to the end of the string to fill the given width if width > length of string. Left justified string.

+

Syntax:

+
str.ljust(width, fillchar = ' ')
+
+

IN [55]

+
s1 = 'hii'
+s1.ljust(5, '*')
+
+

27. rjust:

+

Pads given char (default - space) to the start of the string to fill the given width if width > length of string. Right justified string.

+

Syntax:

+
str.rjust(width, fillchar = ' ')
+
+

IN [57]

+
s1 = 'hii'
+s1.rjust(5)
+
+

28. sorted:

+

Returns sorted string as a list based on given key.

+

Syntax:

+
sorted(iterable, key = None, reverse = False)
+
+

IN [58]

+
s1 = 'hii'
+sorted(s1)
+
+

Accessing Elements in a string:

+

Elements of a string can be accessed using index.

+

Example:
+Consider a string,

+
s = 'Hello'
+
+

Length = 5

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Element‘H’‘e’‘l’‘l’‘o’
Position12345
Positive Index01234
Negative Index-5-4-3-2-1
+

Calling $i^{th}$ element:
+positive index: s [i-1]
+negative index: s [i - 1 - length]

+

IN [1]

+
s1 = 'Hello'
+print(s1[0])
+print(s1[-2])
+
+

stdout

+
H
+l
+
+
+

Slicing operator:

+

Used to get a substring of a string. Denoted by []

+

Syntax:

+
string_name[start = 0 : stop = length : stride = 1]
+
+

IN [60]

+
s1 = 'Python is Easy to Learn'
+s1[5:-3]
+
+

Printing the elements in a string:

+
    +
  1. Using loops
  2. +
  3. Using *
  4. +
+

1. Looping:

+

Use for or while loop to access element or string.

+

2. Using * :

+

Using * will convert the characters in the string into arguements of print method

+

IN [2]

+
s2 = 'Welcome'
+for i in s2:
+    print(i, end='')
+
+

stdout

+
Welcome
+
+

IN [1]

+
s3 = 'Python Programming'
+for i in range(len(s3)):
+    print(s3[i], end='')
+
+

stdout

+
Python Programming
+
+

IN [61]

+
s2 = 'Book'
+print(*s2)
+
+

stdout

+
B o o k
+
+
+

Working with ASCII values:

+

Two built in methods, ord and chr can be used to work with ASCII values.

+

1. ord:

+

Returns the decimal ASCII (ordinal) value or Unicode point of given one-character string.

+

Syntax:

+
ord(c)
+
+

2. chr:

+

Returns the one character Unicode or ASCII string of given ordinal.

+

Syntax:

+
chr(i)
+
+

IN [1]

+
s = 'a'
+ord(s)
+
+

IN [2]

+
o = 97
+chr(o)
+
+

String Comparison:

+

Python allows usage of relational operators on strings.

+

Python compares two strings using Lexicographical order (dictionary arrangement), i.e. using ASCII values of these characters.
+This means that ‘B’(ASCII value = 66) is smaller than ‘b’ (ASCII value = 98)

+

IN [3]

+
sample1 = 'Python'
+sample2 = 'midhun'
+sample1 > sample2
+
+

IN [5]

+
sample1 = 'PYTHON'
+sample2 = 'pYTHON'
+sample1 < sample2
+
+

IN [1]

+
sample1 = 'Hi'
+sample2 = 'Hello'
+sample1 > sample2
+
+

Some other methods in Python Strings:

+
    +
  1. max
  2. +
  3. min
  4. +
  5. reversed
  6. +
  7. splitlines
  8. +
  9. format
  10. +
+

1. max:

+

Returns the maximum value in the given string. Returns the character with maximum ASCII value in the String by default.

+

Syntax:

+
max(String, key = None)
+
+

IN [9]

+
s = 'hello'
+max(s)
+
+

IN [10]

+
s = 'hello'
+max(s, key = lambda x: s.count(x))
+
+

2. min:

+

Returns minimum value in the string. Returns the character with minimum ASCII value in the String by default.

+

Syntax:

+
min(iterable, key = None)
+
+

IN [13]

+
s = 'hello'
+min(s)
+
+

3. reversed:

+

Returns iterator object of reversed string.

+

Syntax:

+
revrsed(sequence)
+
+

IN [14]

+
s = 'hello'
+for i in reversed(s):
+    print(i, end='')
+
+

stdout

+
olleh
+
+

4. splitlines:

+

Returns a list of strings split with carriage return and line feed (CRLF) as separator.

+

Syntax:

+
str.splitlines(keepends = False)
+
+

IN [19]

+
s1 = 'Hello\n\rPython'
+s1.splitlines()
+
+

IN [18]

+
s1 = 'Hello\n\rPython'
+s1.splitlines(keepends = True)
+
+

5. format:

+

Returns formatted string as required.

+

Syntax:

+
str.format(*args, **kwargs)
+
+

It was already discussed at String formatting in Introduction to Python Programming

+

String Formatting:

+

Refer discussion in Introduction to Python Programming

+
+ + + + + \ No newline at end of file diff --git a/docs/DS_Tuples.html b/docs/DS_Tuples.html new file mode 100644 index 0000000..6386262 --- /dev/null +++ b/docs/DS_Tuples.html @@ -0,0 +1,539 @@ + + + + + + + + Data Structures or Derived data Types in Python: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Data Structures or Derived data Types in Python:

+ +

Storing multiple values of same or different types under a single name. + They are collection of data.

+
    +
  1. List
  2. +
  3. Tuple
  4. +
  5. String
  6. +
  7. Dictionary
  8. +
  9. Set
    + In this notebook, we’ll discuss indepth on Tuples
  10. +
+

Tuple:

+

Tuples are ordered collection of data. Unlike Lists they are immutable. + Represented by parenthesis ‘( )’

+
tuple : (10, 20, 30, 'Hello', -2.0)
+
+

Each value in the tuple is called a element
+ order of elements: index of element
+ Index - may be positive or negative

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Order (element)FirstSecondThirdLast
Positive Index012n-1
Negative Index-n-n+1-n+2-1
+

Defining a tuple:

+
    +
  1. ’( )’
  2. +
  3. tuple()
  4. +
+

1. ‘( )’

+
l = (10, 20, 30)
+
+

add a comma ‘,’ if tuple is singleton,

+
t = (10,)
+
+

2. tuple()

+

Syntax:

+
tuple(iterable = None)
+
+

iterable: any data structures listed above

+

IN [9]

+
t = (10, 30)
+print(t)
+print(type(t))
+
+

stdout

+
(10, 30)
+<class 'tuple'>
+
+
+

IN [8]

+
t1 = (10,)
+print(t1)
+print(type(t1))
+
+

stdout

+
(10,)
+<class 'tuple'>
+
+
+

IN [3]

+
t2 = tuple()
+print(t2)
+print(type(t2))
+
+

stdout

+
()
+<class 'tuple'>
+
+
+

Working with tuples:

+
    +
  1. Concatenation
  2. +
  3. Appending
  4. +
  5. Multiplication
  6. +
+

1. Concatenation:

+

Two tuples can be concatenated by using + operator.

+

IN [4]

+
t1 = (10, 20)
+t2 = (30,)
+print(t1 + t2)
+
+

stdout

+
(10, 20, 30)
+
+
+

2. Appending:

+

A tuples can be appended to string using += operator or by reassignment.

+

IN [5]

+
t1 = (10, 20)
+t2 = (30,)
+t1 += t2
+print(t1)
+
+

stdout

+
(10, 20, 30)
+
+
+

3. Tuple Multiplication:

+

Tuple multiplication results a new tuple with repitition. It can be done using * operator.

+

IN [6]

+
t1 = (10, 20)
+print(t1 * 5)
+
+

stdout

+
(10, 20, 10, 20, 10, 20, 10, 20, 10, 20)
+
+
+

Methods or Functions in tuple:

+

There are various methods or functions that are used to work on tuples.

+
    +
  1. map
  2. +
  3. filter
  4. +
  5. sorted
  6. +
  7. index
  8. +
  9. reduce
  10. +
  11. reversed
  12. +
  13. len
  14. +
  15. count
  16. +
  17. sum
  18. +
  19. max
  20. +
  21. min
  22. +
  23. enumerate
  24. +
  25. zip
  26. +
+

1. map:

+

Applies the given function to every element in a iterable.

+

Syntax:

+
map(function, iterable)
+
+

IN [10]

+
def sample_fn(x):
+    return x + 2
+t = [1, 2, 3, 4]
+t = tuple(map(sample_fn, t))
+print(t)
+
+

stdout

+
(3, 4, 5, 6)
+
+
+

2. filter:

+

Filters out the elements that match the given condition

+

Syntax:

+
filter(condition, iterable)
+
+

The condition should be given as a function definition which can be mapped to each variable.

+

IN [17]

+
t = (1, -1, 0, 3, -10, 100)
+t2 = tuple(filter(lambda x: x>0, t)) # A Lambda function used for condition
+print(t2)
+
+

stdout

+
(1, 3, 100)
+
+
+

3. sorted:

+

Sorts the given tuple and returns a copy

+

Syntax:

+
sorted(iterable, key = None, reverse = False)
+
+

IN [11]

+
l2 = (10, 20, 50, 0, -10, -1, 100)
+l2 = tuple(sorted(l2))
+print(l2)
+
+

stdout

+
(-10, -1, 0, 10, 20, 50, 100)
+
+
+

4. index:

+

Returns the index of the element in the tuple. If multiple elements exist, it gives the index of first + occurrence. If the element is not in the tuple, it raises an error

+

Syntax:

+
tuple.index(element)
+
+

IN [12]

+
l = (10, 20, 30, 40, 10)
+print(l.index(10))
+
+

stdout

+
0
+
+
+

5. reduce:

+

Sequentially applies the elements in the tuple to a function to give the final value. To use this we need to + call functools module. In depth study of modules will be dealt later

+

Syntax:

+
reduce(function, tuple)
+
+

IN [13]

+
from functools import reduce
+
+def add(x, y):
+    return x+y
+
+l = (10, 20, 30, 40)
+c = reduce(add, l)
+print(c)
+
+

stdout

+
100
+
+
+

Explanation:

+

Step 1: + applies 10 and 20 to the function. result = 30

+

Step 2: + applies the result and next element (30). result = 60

+

Step 3: + applies the result and next element (40). result = 100

+

End is reached. so the result 100 is returned

+

6. reversed:

+

Returns iterator object of reversed tuple.

+

Syntax:

+
revrsed(sequence)
+
+

IN [22]

+
s = (10, 20, 30)
+for i in reversed(s):
+    print(i, end=' ')
+
+

stdout

+
30 20 10 
+
+

7. len:

+

Returns the length of the given iterable

+

Syntax:

+
len(iterable)
+
+

IN [14]

+
list2 = (10, 20, 30, -1, 123, 10.0)
+print(len(list2))
+
+

stdout

+
6
+
+
+

8. count:

+

Returns the count of the element specified

+

Syntax:

+
tuple.count(element)
+
+

IN [15]

+
l = (10, 20, 30, 10, 20, 25, 20, 50)
+print(l.count(20))
+print(l.count(10))
+
+

stdout

+
3
+2
+
+
+

9. sum:

+

Returns the sum elements in the tuple.

+

Syntax:

+
sum(tuple, start = 0)
+
+

IN [16]

+
l = (10, -10, 20, -30, 40)
+print(sum(l))
+
+

stdout

+
30
+
+
+

10. max:

+

Returns the maximum value in the tuple.

+

Syntax:

+
max(tuple, key = None)
+
+

IN [17]

+
l = (10, 15, 50, 21, -7)
+print(max(l))
+
+

stdout

+
50
+
+
+

IN [18]

+
l = (10, 15, 50, 21, -7, 7)
+print(max(l, key=lambda x: x % 5)) # Maximum reminder when divided by 5
+
+

stdout

+
-7
+
+
+

11. min:

+

Returns minimum value in the iterable

+

Syntax:

+
min(iterable, key = None)
+
+

IN [19]

+
l = (10, 15, 50, 21, -7)
+print(min(l))
+
+

stdout

+
-7
+
+
+

IN [20]

+
l = (10, 15, 50, 21, -7, 10.0)
+print(min(l))
+
+

stdout

+
-7
+
+
+

12. enumerate:

+

Returns the enumerate object for given tuple. An enumerate object is an iterable which contains ordered pair + of the form (index, value)

+

Syntax:

+
enumerate(iterable, start = 0)
+
+

IN [21]

+
l = (10, 20, 'Hello', 'a', -1)
+print(tuple(enumerate(l)))
+
+

stdout

+
((0, 10), (1, 20), (2, 'Hello'), (3, 'a'), (4, -1))
+
+
+

13. zip:

+

Returns zipped object containing order pairs of elements from given iterables.

+

Syntax:

+
zip(iterables)
+
+

IN [40]

+
l = (10, 15, 50, 21, -7, 8)
+t = ['Ten', 'Fifteen', 'Fifty', 'Twenty One', 'Negative Seven']
+print(*zip(l, t))
+
+

stdout

+
(10, 'Ten') (15, 'Fifteen') (50, 'Fifty') (21, 'Twenty One') (-7, 'Negative Seven')
+
+
+

Accessing Elements in a tuple:

+

Elements of a tuple can be accessed using index.

+

Example:
+ Consider a tuple,

+
t = (10, 20, 30, 40, 50)
+
+

Length = 5

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Element1020304050
Position12345
Positive Index01234
Negative Index-5-4-3-2-1
+

Calling $i^{th}$ element:
+ positive index: t [i-1]
+ negative index: t [i - 1 - length]

+

Slicing operator:

+

Used to get / set a sub-tuple of a tuple. Denoted by []

+

Syntax:

+
tuple_name[start = 0 : stop = length : step = 1]
+
+

IN [22]

+
t = (10, 20, 30, 40)
+print(t[:3])
+
+

stdout

+
(10, 20, 30)
+
+
+

Printing the elements in a tuples:

+
    +
  1. Using loops
  2. +
  3. Using *
  4. +
+

1. Looping:

+

Use for or while loop to access elements.

+

2. Using * :

+

Using * will convert the tuple elements into individual arguments of print method

+

IN [2]

+
# for loop to get index
+l = (10, 20, 30, 40, 50)
+for i in range(len(l)):
+    print(l[i], end= ' ')
+
+

stdout

+
10 20 30 40 50 
+
+

IN [3]

+
# Using *
+l = (10, 20, 30, 40, 50)
+print(*l)
+
+

stdout

+
10 20 30 40 50
+
+
+

List Comprehension in tuples:

+

It follows the form of the mathematical set-builder notation unlike the use of map and filter functions. It + is used to create tuples from either an existing one or a completely new tuple.

+

Set builder form: + $\{x: x ~\rm{\epsilon~ iterable}\}$
+ Example:

+
t = tuple(expression (loops))
+
+

IN [9]

+
# comprehension
+l = [10, 20, 30, 40, 50]
+s = tuple(i**2 for i in l) # squares of elements in list l using comprehension
+sq = list(map(lambda x: x**2, l)) # Using map
+print(*s)
+print(*sq)
+
+

stdout

+
100 400 900 1600 2500
+100 400 900 1600 2500
+
+
+

Multi-dimensional tuples or matrices:

+

Like Lists, tuples / lists in a tuple is called a multidimensional tuple or nested tuple. They are generally + used to store matrices.

+

Example:

+
t = ((10, 20, 30), (40, 50, 60))
+# Two dimensional tuple
+
+

Accessing elements using index:

+

Syntax:

+
tuple_name[outermost_tuple_index][inner]...[inner_most_index]
+
+

Matrix:

+

A rectangular array of elements. Two dimensional lists or tuples are used to work with matrices.

+

Each row of matrix is stored as a list / tuple

+

Example:

+
matrix = ([10, 20, 30], (40, 50, 60))
+
+

Matrix input:

+

Matrix can be taken as input using loops or list comprehension.

+

Output:

+

Output is printed using for loop

+

Variable length argument Tuples:

+

The input given to variable length arguements are gathered together to form a tuple

+

Tuple Comparison:

+

Python allows usage of relational operators on Tuples.

+

Python compares two tuples using the elements present in them. Whenever a greater element is encounter the + boolean value is returned.

+
+ + + + + \ No newline at end of file diff --git a/docs/Errors_and_Exception.py b/docs/Errors_and_Exception.py new file mode 100644 index 0000000..c1f5948 --- /dev/null +++ b/docs/Errors_and_Exception.py @@ -0,0 +1,12 @@ +def a(): + print("In a") + b() + print("Back in a") + + +def b(): + print("In b") + return 42 / 0 + + +a() diff --git a/docs/Errors_and_Exception_Handling.html b/docs/Errors_and_Exception_Handling.html new file mode 100644 index 0000000..a254a92 --- /dev/null +++ b/docs/Errors_and_Exception_Handling.html @@ -0,0 +1,445 @@ + + + + + + + + Errors and Exception + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Errors and Exception

+ +

Error:

+

Errors are the problems in a program due to which the program will stop the execution.

+

Some Common Errors

+
    +
  1. Syntax Errors
  2. +
  3. Run-time Errors
  4. +
  5. Logical Errors
  6. +
  7. Latent Errors
  8. +
+

IN [10]

+
# list of Errors and exceptions
+for i in dir(__builtins__) + dir(__builtin__):
+    if "Error" in i:
+        print(i)
+
+

stdout

+
ArithmeticError
+AssertionError
+AttributeError
+BlockingIOError
+BrokenPipeError
+BufferError
+ChildProcessError
+ConnectionAbortedError
+ConnectionError
+ConnectionRefusedError
+ConnectionResetError
+EOFError
+EnvironmentError
+FileExistsError
+FileNotFoundError
+FloatingPointError
+IOError
+ImportError
+IndentationError
+IndexError
+InterruptedError
+IsADirectoryError
+KeyError
+LookupError
+MemoryError
+ModuleNotFoundError
+NameError
+NotADirectoryError
+NotImplementedError
+OSError
+OverflowError
+PermissionError
+ProcessLookupError
+RecursionError
+ReferenceError
+RuntimeError
+SyntaxError
+SystemError
+TabError
+TimeoutError
+TypeError
+UnboundLocalError
+UnicodeDecodeError
+UnicodeEncodeError
+UnicodeError
+UnicodeTranslateError
+ValueError
+WindowsError
+ZeroDivisionError
+ArithmeticError
+AssertionError
+AttributeError
+BlockingIOError
+BrokenPipeError
+BufferError
+ChildProcessError
+ConnectionAbortedError
+ConnectionError
+ConnectionRefusedError
+ConnectionResetError
+EOFError
+EnvironmentError
+FileExistsError
+FileNotFoundError
+FloatingPointError
+IOError
+ImportError
+IndentationError
+IndexError
+InterruptedError
+IsADirectoryError
+KeyError
+LookupError
+MemoryError
+ModuleNotFoundError
+NameError
+NotADirectoryError
+NotImplementedError
+OSError
+OverflowError
+PermissionError
+ProcessLookupError
+RecursionError
+ReferenceError
+RuntimeError
+SyntaxError
+SystemError
+TabError
+TimeoutError
+TypeError
+UnboundLocalError
+UnicodeDecodeError
+UnicodeEncodeError
+UnicodeError
+UnicodeTranslateError
+ValueError
+WindowsError
+ZeroDivisionError
+
+
+

Exception:

+

Exceptions are raised when the some internal events occur which changes the normal flow of the program.

+

IN [9]

+
# list of Errors and exceptions
+for i in dir(__builtins__) + dir(__builtin__):
+    if "Exception" in i:
+        print(i)
+
+

stdout

+
BaseException
+Exception
+BaseException
+Exception
+
+
+

Traceback

+

The script used below is present here

+

IN [11]

+
def a():
+    print("In a")
+    b()
+    print("Back in a")
+
+def b():
+    print("In b")
+    return 42/0
+
+a() 
+
+

stdout

+
In a
+In b
+
+
+

Error

+
In a
+
+In b
+
+
+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 10, in <module>
+
+    a() 
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 3, in a
+
+    b()
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 8, in b
+
+    return 42/0
+
+ZeroDivisionError: division by zero
+
+
+

Exception Handling:

+

Marking the error-prone zone and controlling what happens when an error / exception is raised is Exception Handling.

+

In python, Exception Handling can be done using the following:

+
    +
  1. try block
  2. +
  3. except block
  4. +
  5. else block
  6. +
  7. finally block
  8. +
+

Syntax:

+
try:
+    # Statements - Critical or Error Prone statements
+except ErrorOrExceptionType:
+    # Statements - What to do to handle errors
+else:
+    # Statements - What to do when error is not encountered
+finally:
+    # Statements - What to do at the end of Exception Handling
+
+

1. try block:

+

The critical operation that might not work as indented or may malfunction is enclosed in the try block. If the statement(s) raise any Error, the execution proceeding in the try block is terminated and moved to except block

+
try:
+    # Statement(s) that may cause Errors
+
+

2. except block

+

The except block accepts the error/exception call and works as intended. The except block is used to filter the error that is anticipated.

+
except ErrorOrException:
+
+

The proper way of defining the except block is as above.
+Though leaving out the Error name part works fine, it may cause a lot of confusion in many cases and is not recommended

+
except: # Not recommended for use
+
+

IN [2]

+
# Example
+try:
+    n = input()
+    print(n / 10)
+except TypeError:
+    print("Error occurred")
+
+

stdin

+
 123
+
+
+

stdout

+
Error occurred
+
+
+

IN [3]

+
# Example - not recommended
+try:
+    n = input()
+    print(n / 10)
+except: # Don't do it this way
+    print("Error occurred")
+
+

stdin

+
 159
+
+
+

stdout

+
Error occurred
+
+
+

3. else block

+

If there is no error in the code inside try block, the except block is skipped and the else block is executed.

+
else:
+    # Statement(s) to run when no error is caused
+
+

IN [6]

+
# Example
+try:
+    n = int(input())
+    print(10 / n)
+except ZeroDivisionError: # Catch when there is division by zero (0)
+    print("Error occurred")
+else:
+    print("Safe")
+
+

stdin

+
 10
+
+
+

stdout

+
1.0
+Safe
+
+
+

4. finally block

+

This block is executed at all cases, whether or not an error is encountered inside the try block

+
finally:
+    # Statement(s)
+
+

IN [1]

+
# Example
+try:
+    n = int(input())
+    print(10 / n)
+except ZeroDivisionError: # Catch when there is division by zero (0)
+    print("Error occurred")
+else:
+    print("Safe")
+finally:
+    print("End of Program")
+
+

stdin

+
 0
+
+
+

stdout

+
Error occurred
+End of Program
+
+
+

as keyword in except

+

Almost any case of exceptions returns a message about the cause of the error. The above defined method does not get the message for use.

+

Using as keyword, the error message can stored in a variable for use inside the except block.

+
except ErrorOrException as err:
+    # Statement(s)
+
+

IN [2]

+
# Example
+try:
+    n = int(input())
+    print(10 / n)
+except ZeroDivisionError as e: # Catch when there is division by zero (0)
+    print("Error occurred -", e) 
+    # The message 'division by zero' is stored in e for use in the except block
+else:
+    print("Safe")
+finally:
+    print("End of Program")
+
+

stdin

+
 0
+
+
+

stdout

+
Error occurred - division by zero
+End of Program
+
+
+

Intentionally Raising an Exception:

+

Python allows you to intentionally raise an exceptio at some cases using raise keyword.

+

Syntax:

+
raise ExceptionName("Message")
+
+

It is important to note that the exception following the raise keyword should either be an instance of a built-in exception or a class inheriting the same (Custom Exception).

+

IN [5]

+
# Example - Kelvin to Celsius Conversion
+t = int(input("Enter temperature in Kelvin"))
+if t < 0:
+    raise ValueError("The minimum temperature in Kelvin is absolute zero (0)")
+else:
+    print(t - 273.15)
+
+

stdin

+
Enter temperature in Kelvin -1
+
+
+

Error

+
Enter temperature in Kelvin
+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 2, in <module>
+
+    t = int(input("Enter temperature in Kelvin"))
+
+ValueError: invalid literal for int() with base 10: 'Enter temperature in Kelvin -1'
+
+
+

Assertion statement:

+

An assertion is a sanity-check that you can turn on or turn off for testing your program.

+

The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression or condition is tested, and if the result comes up false, an exception is raised.

+

assert Statement:

+

When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.

+
assert expression, "Error message"
+
+

The assert statement is usually enclosed by a try block and the exception is handled. In some cases to terminate the execution, they may not be used.

+

IN [7]

+
# Example - Kelvin to Celsius Conversion
+t = int(input("Enter temperature in Kelvin"))
+try:
+    assert t > 0, "The minimum temperature in Kelvin is absolute zero (0)"
+except AssertionError as err:
+    print(err)
+else:
+    print(t - 273.15)
+
+

stdin

+
Enter temperature in Kelvin -1
+
+
+

stdout

+
The minimum temperature in Kelvin is absolute zero (0)
+
+
+

Creating custom Errors/Exception from built-ins:

+

Python has numerous built-in exceptions that force your program to output an error when something in the program goes wrong.

+

However, sometimes you may need to create your own custom exceptions that serve your purpose.

+

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

+
class My_exception(Exception):
+    pass
+
+

To know more about classes, visit Object Oriented Programming

+

IN [8]

+
class My_exception(Exception):
+    pass
+
+n = int(input())
+if n > 100:
+    raise My_exception("Number is large")
+else:
+    print(2 * n)
+
+

stdin

+
 101
+
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 6, in <module>
+
+    raise My_exception("Number is large")
+
+__main__.My_exception: Number is large
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/Functions.html b/docs/Functions.html new file mode 100644 index 0000000..5bbc251 --- /dev/null +++ b/docs/Functions.html @@ -0,0 +1,713 @@ + + + + + + + + Functions in Python + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Functions in Python

+ +

Function is a set of organized lines of code that performs a specific, well defined task.

+

It is used reduce the number of lines of code and improve reusability.

+

Syntax:

+
def function_name(parameters):  # function definition  
+    Statements
+    return value(s)
+
+...  
+...  
+function_name(parameters) # Caller
+
+

Return statement:

+
return
+
+

Returns back a value as specified. It marks the end of a function

+

Fruitful function

+

A fruitful function is a function that returns a value

+

IN [1]

+
# Example 1:
+def add(a, b): # Function Definition
+    return a + b # returns the sum
+x = int(input())
+y = int(input())
+print(add(x, y)) # Function Calling
+# Input:
+# 12
+# 13
+
+

stdin

+
 12
+ 13
+
+
+

stdout

+
25
+
+
+

Naming a function

+

Like variables, python functions should also be in lower_snake_case

+

One of the more universal, yet simple rules is: Function names should be verbs if the function changes the state of the program, and nouns if they’re used to return a certain value.

+
    +
  1. Self-explanatory names: a function get_name() will tell the developer what it returns as well as set_address(), is_male(), etc.
  2. +
  3. Short: a function name must be as short as possible so that it’s simple to type as well as easy to remember. A function get_number_of_pages_in_the_book() is not good, something like get_book_page_count() is better.
  4. +
  5. Use of prefixes: use prefixes in the functions such as get_name(), set_name(), etc.
  6. +
+

The most important thing to note is to follow a constant naming convention throughout the function

+

Lambda function (Inline or Anonymous function):

+

One liner of a function. It is created for use at one point or one statememt and is not intended to be named and stored.

+

Syntax:

+
lambda parameters: Statement
+
+

IN [9]

+
# Example 1
+
+def is_even(x):
+    return x % 2 == 0 # One line function to check if even
+
+a = int(input())
+print("From is_even(x):", is_even(a))
+print("From lambda:", (lambda x: x % 2 == 0)(a)) # Equivalent lambda function
+
+# Input: 10
+
+

stdin

+
 10
+
+
+

stdout

+
From is_even(x): True
+From lambda: True
+
+
+

The lambda function is generally created for use with iterables where the function is applied to several values but at only once (that part of the code).

+

The usual places include maps, filter and keys for sorting for any iterable. Visit Lists or Tuples to know more on them

+

Recursion:

+

Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem.

+

Recursive function:

+

A function that performs recursion.

+

A recursive function calls itself repeatedly by dividing the problem into sub problems until the solution is obtained for the smallest sub-problem.

+
def function(paramters1):
+    function(parameters2) # Recursive calling
+
+

IN [14]

+
# Example using factorial (n! = 1 * 2 * 3 ... n) n! = n * (n-1)!
+def factorial(n):
+    if -1<n<=1: return 1 # End of recursion
+    else: return n * factorial(n-1) # recursive calling
+
+n = int(input())
+print(factorial(n))
+# Input: 6
+
+

stdin

+
 6
+
+
+

stdout

+
720
+
+
+

Breaking down of problem:

+
n = 6  
+n <= 1 False  
+6 * factorial(5)  
+
+n = 5  
+n <= 1 False  
+5 * factorial(4)  
+
+n = 4  
+n <= 1 False  
+4 * factorial(3)  
+
+n = 3  
+n <= 1 False  
+3 * factorial(2)  
+
+n = 2  
+n <= 1 False  
+2 * factorial(1)  
+
+n = 1  
+n <= 1 (n==1) True  
+1
+
+Building up:
+
+1
+2 * 1  
+3 * 2 * 1  
+4 * 3 * 2 * 1  
+5 * 4 * 3 * 2 * 1  
+6 * 5 * 4 * 3 * 2 * 1  
+
+720
+
+

You can find the steps in recursion below
+The ‘|’ line indicates the same level of recursive call

+

IN [5]

+
# The indent paramter defines the offset of output. This program is to understand recursion only.
+def fact(n, indent=''):
+    print(indent, n, sep='')
+    if 0 <= n <= 1: return 1
+    else:
+        fac = n * fact(n-1, indent + "|\t")
+        print(indent, fac, sep='')
+        return fac
+
+fact(6)
+
+

stdout

+
6
+|   5
+|   |   4
+|   |   |   3
+|   |   |   |   2
+|   |   |   |   |   1
+|   |   |   |   2
+|   |   |   6
+|   |   24
+|   120
+720
+
+
+

Function Arguments or Parameters: (args or params)

+

Values passed into a function. They are optional

+
Types:
+
    +
  1. Required Arguments
  2. +
  3. Keyword Arguements
  4. +
  5. Default Arguments
  6. +
  7. Variable length Arguments
  8. +
+

1. Required Arguments:

+

Positional Arguments. +These are arguments required to execute a function.
+The number of required arguments should be equal to the number of arguments passed. +If not, it will result in error.

+

IN [29]

+
# Example 
+def add(a, b): # Function Definition - no. of required arguments
+    return a+b # returns the sum
+x = int(input())
+y = int(input())
+print(add(x, y)) # Function Calling - no. of args passed
+
+# Input:
+# 12
+# 23
+
+

stdin

+
 12
+ 23
+
+
+

stdout

+
35
+
+
+

IN [30]

+
#Example
+# Example 
+def add(a, b): # Function Definition - no. of required arguments
+    return a+b # returns the sum
+x = int(input())
+y = int(input())
+print(add(x)) # Function Calling - no. of args passed < no. of required args
+
+

stdin

+
 10
+ 23
+
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 7, in <module>
+
+    print(add(x)) # Function Calling - no. of args passed < no. of required args
+
+TypeError: add() missing 1 required positional argument: 'b'
+
+
+

2. Keyword arguments (kwargs):

+

These arguments are not positional but are required.

+

IN [20]

+
# Example 2
+def add(a, b): # Function Definition - Parameters
+    print(a, b)
+    return a+b # returns the sum
+
+
+x = int(input())
+y = int(input())
+print(add(b = x, a = y)) # Function Calling - Keywords are names of params used in definition
+# Input: 10
+# 23
+
+

stdin

+
 10
+ 23
+
+
+

stdout

+
23 10
+33
+
+
+

3. Default arguments:

+

Arguments which are optional. They have values by default.

+

IN [31]

+
#Example 
+def add(a, b = 0): # Function Definition - b is default args
+    print(a, b)
+    return a+b # returns the sum
+x = int(input())
+y = int(input())
+
+# b given in function call
+print('B given')
+print(add(x, y)) # Function Calling
+
+print()
+
+# b not given in function call
+print('B not given default = 0')
+print(add(x)) # Function Calling
+
+# Input: 12
+# 23
+
+

stdin

+
 12
+ 23
+
+
+

stdout

+
B given
+12 23
+35
+
+B not given default = 0
+12 0
+12
+
+
+

Defining or indicating the difference in the type of args:

+

From python 3.8, ‘/’ is used to Separate positional args from non positional.

+

IN [32]

+
# Example 
+def add(a, /, b=0): # Function Definition
+    return a+b # returns the sum
+x = int(input())
+y = int(input())
+print(add(x)) # Function Calling 
+# Input: 10
+# 23
+
+

stdin

+
 10
+ 23
+
+
+

stdout

+
10
+
+
+

4. Variable Length Arguments:

+

Args that are used when the number of arguments is not known. +The arguments passed are stored as a tuple. The arguments that start with ‘ * ‘ indicate Variable length arguments and are called gather

+

IN [2]

+
#Example
+# Example 
+def add(a, *b): # Function Definition -  * indicates variable length arguments
+    print(b)
+    return a + sum(b) # returns the sum; sum is a built in function that returns sum of elements in an iterable
+x = int(input())
+y = int(input())
+# 2 arguments
+print(add(x, y))
+print()
+# 3 args
+print(add(x, y, 10))
+print()
+# 4 args
+print(add(x, y, 10, 20)) # Function Calling - no. of args passed
+
+# Input: 10
+# 23
+
+

stdin

+
 10
+ 23
+
+
+

stdout

+
(23,)
+33
+
+(23, 10)
+43
+
+(23, 10, 20)
+63
+
+
+

Types:

+
    +
  1. *args
  2. +
  3. **kwargs
  4. +
+

1. *args:

+

Variable length arguements that are most commonly used. Stores the values as tuple

+

2. **kwargs:

+

Variable length arguments of the form key = value. Stores the values as key-value mapping or dictionary.

+

IN [3]

+
#kwargs example
+def kwargs_ex(**a):
+    print(a)
+    for k, v in a.items():
+        print(f"{k} = {v}")
+
+kwargs_ex(x=2, y=3)
+
+

stdout

+
{'x': 2, 'y': 3}
+x = 2
+y = 3
+
+
+

Scope of variable:

+

The part of code where a variable can be accessed. +Scopes: +1. Global Variable +2. Local Variable

+

1. Global Variable:

+

Variable that can be acessed in any part of the program.

+

2. Local Variable:

+

Variable that can be accessed only inside a specific block or part of a program.

+

IN [7]

+
#Example
+def add(a, b): 
+    c = a+b
+    print(c)
+    #return a+b
+
+def printf():
+    print(k)
+
+x = int(input('x:'))
+y = int(input('y:'))
+add(x,y)
+print('Hello')
+s = 10
+z = -100
+for i in range(5):
+    k = 'Hello'
+    print(k)
+print(x,y,s,z)
+printf()
+print(k)
+print(i)
+print(c)
+
+# Input:
+# 10
+# 23
+
+

stdin

+
x: 10
+y: 23
+
+
+

stdout

+
33
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+10 23 10 -100
+Hello
+Hello
+4
+
+
+

Error

+
x:
+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 10, in <module>
+
+    x = int(input('x:'))
+
+ValueError: invalid literal for int() with base 10: 'x: 10'
+
+
+

IN [9]

+
def printf(): # Function definition
+    global k
+    k = 'Hi' #Local Variable Gloablized
+    print(k)
+
+for i in range(5):
+    k = 'Hello' # Global Variable
+    print(k) 
+
+printf()
+print(k)
+
+

stdout

+
Hello
+Hello
+Hello
+Hello
+Hello
+Hi
+Hi
+
+
+

Docstrings in Function:

+

Docstrings are most commonly used in a function. +They act as descriptor of function, i.e., they describe the function.

+

Calling docstings:

+
function_name.__doc__
+
+

IN [1]

+
def fn():
+    '''This is a docstring'''
+print(fn.__doc__) # Calls docstring
+
+

stdout

+
This is a docstring
+
+
+

Recursion vs Iteration:

+

Recursion involves calling function repeatedly to breakdown a problem.
+Iteration is solving the problem by breaking down using loops.

+

Recursion is a easy way to solve a problem. But it is a bit time consuming. +Iteration is hard coding but is efficient in solving the problems.

+

This brings in a new programming stream called Dynamic Programming.

+

Functions seen so far:

+
    +
  1. print
  2. +
  3. input
  4. +
  5. int
  6. +
  7. float
  8. +
+

1. print:

+

Syntax:

+
print(values, end="\n", sep" ")
+
+

IN [3]

+
print(1,2,3, sep = "") # no separation between the values
+
+

stdout

+
123
+
+
+

IN [4]

+
print(1,2,3)
+
+

stdout

+
1 2 3
+
+
+

IN [5]

+
print(1,2,3, sep = '\t')
+
+

stdout

+
1   2   3
+
+
+

IN [6]

+
print(1,2,3)
+print(4,5)
+
+

stdout

+
1 2 3
+4 5
+
+
+

IN [7]

+
print(1,2,3, end='')# end of print is <none>
+print(4,5)
+
+

stdout

+
1 2 34 5
+
+
+

IN [8]

+
print(1,2,3, end=' ') # end of print is <space>
+print(4,5)
+
+

stdout

+
1 2 3 4 5
+
+
+

2. input:

+

Syntax:

+
input(prompt="")
+
+

IN [10]

+
n = input()
+
+# Input: 20
+
+

stdin

+
 20
+
+
+

IN [11]

+
a = input(prompt = 'Prompt')
+
+# Input: 10
+
+

stdin

+
Prompt 10
+
+
+

3. int:

+

Syntax:

+
int(x, base = 10)
+
+

IN [13]

+
int('10')
+
+

IN [14]

+
b = '110'
+int(b, 2)
+
+

IN [15]

+
x = '7af'
+int(x, 16)
+
+

IN [17]

+
o = '75'
+int(o, 8)
+
+

4. float:

+

Syntax:

+
float(x = 0)
+
+

IN [20]

+
float()
+
+

IN [21]

+
float ('1.2')
+
+

IN [22]

+
float(1)
+
+

IN [24]

+
float('12') 
+
+

Multiple Functions with same name:

+

Python does not allows multiple functions with different parameters with same name. If so exist, the last function definition replaces the first.

+

IN [25]

+
def fn():
+    return 'Hi'
+def fn(x,y):
+    return x+y
+print(fn())
+print(fn(10, 5))
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 5, in <module>
+
+    print(fn())
+
+TypeError: fn() missing 2 required positional arguments: 'x' and 'y'
+
+
+

Gather vs Scatter:

+

Argument given to var. args are gathered and stored together to form a tuple. This is called gather.

+

Argument given as a list/tuple is split across required variable. This is called scatter

+

IN [2]

+
#Example
+def add(a, *b): # Function Definition 
+    print(a, b)
+    return a + sum(b) # returns the sum; sum is a built in function that returns sum of elements in an iterable
+
+l = list(map(int, input().split()))
+print(add(*l)) # Function Calling
+
+# Input: 10
+# 23
+# 30
+# 40
+
+

stdin

+
 10 23 30 40
+
+
+

stdout

+
10 (23, 30, 40)
+103
+
+
+

Higher Order Functions or Function Decorators:

+

A function returning another function is called a higher order function

+
def function1(params):
+    def function2(params):
+        Statements
+
+    return function2
+
+

IN [13]

+
def deco(k): # Higher order function / decorator
+    def multiple(n):
+        return n*k
+    return multiple
+
+second_multiple = deco(2)
+n = int(input("Enter a num\n"))
+print(second_multiple(n))
+
+

stdin

+
Enter a num
+ 6
+
+
+

stdout

+
12
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/Generators.html b/docs/Generators.html new file mode 100644 index 0000000..1ce1892 --- /dev/null +++ b/docs/Generators.html @@ -0,0 +1,163 @@ + + + + + + + + Generators in Python: + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Generators in Python:

+ +

Syntax similar to function but are used to generate values.

+

New instances are not created everytime the function is called.

+

Types:

+
    +
  1. Function type generators
  2. +
  3. Inline generators
  4. +
+

1. Function type:

+

Definition as a function. Difference is that it uses yield instead of return.

+

IN [1]

+
def my_first_generator(): # Defining a generator
+    i = 1
+    while i<=100:
+        yield i
+        i += 1
+for j in my_first_generator(): # Calling a generator
+    print(j, end=' ')
+
+

stdout

+
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 
+
+

2. Inline generators:

+

List comprehension inside paranthesis give inline generators.
+Syntax: generator_name = (...List Comprehension...)

+

IN [1]

+
gen = ( 2*i for i in range(10) ) # Definition of a generator
+for i in gen:
+    print(i)
+
+

stdout

+
0
+2
+4
+6
+8
+10
+12
+14
+16
+18
+
+
+

next method:

+

Returns the next element of the generator.

+

Syntax: generator.__next__()

+

IN [5]

+
def my_first_generator(): # Defining a generator
+    i = 1
+    while i<=100:
+        yield i
+        i += 1
+gen = my_first_generator()
+for j in range(50): # Calling a generator
+    print(gen.__next__())
+
+

stdout

+
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+
+
+

IN [7]

+
gen = ( 2*i for i in range(10) ) # Definition of a generator
+for i in range(5):
+    print(gen.__next__())
+
+

stdout

+
0
+2
+4
+6
+8
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/Higher_order_functions.py b/docs/Higher_order_functions.py new file mode 100644 index 0000000..ae9c3db --- /dev/null +++ b/docs/Higher_order_functions.py @@ -0,0 +1,8 @@ +def deco(k): # Higher order function / decorator + def multiple(n): + return n*k + return multiple + +second_multiple = deco(2) +n = int(input("Enter a num\n")) +print(second_multiple(n)) \ No newline at end of file diff --git a/docs/Installing_and_Using_Python.html b/docs/Installing_and_Using_Python.html new file mode 100644 index 0000000..3b05bfb --- /dev/null +++ b/docs/Installing_and_Using_Python.html @@ -0,0 +1,64 @@ + + + + + + + + Installing and Using Python + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Installing and Using Python

+

Downloading and Installing Python

+

The official python software (Interpreter and IDLE) available at the official site

+

For windows 32-bit: Click on Download option in the Downloads Menu

+
+

Using Python

+

The python code can be run in Interactive Console or Script present in IDLE.

+

Other Integrated Development Environments like PyCharm IDE (Jet Brains), Visual Studio (MS) and Net Beans IDE may be used as needed.

+

For Interactive working for beginners, Jupyter Notebooks can be used

+
+

Code Snippets and Tutorials

+

The official Python Documentation may be viewed at or downloaded

+

Other Private tutorials at:

+
    +
  1. Tutorials Point
  2. +
  3. W3Schools
  4. +
  5. Geeks for Geeks
  6. +
+
+

Practice Code at

+
    +
  1. HackerRank
  2. +
  3. HackerEarth
  4. +
+
+ + + + + \ No newline at end of file diff --git a/docs/Introduction_to_Python_Programming.html b/docs/Introduction_to_Python_Programming.html new file mode 100644 index 0000000..c80f35d --- /dev/null +++ b/docs/Introduction_to_Python_Programming.html @@ -0,0 +1,840 @@ + + + + + + + + Introduction to Python Programming + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Introduction to Python Programming

+ +

Program:

+

A set of instructions to perform a specific task

+

Programming Language

+

A language used to write a program

+

Types of Programming language:

+
    +
  1. Statically typed – Compiler; values defined before execution
  2. +
  3. Dynamically typed – Interpreter; values defined during execution
  4. +
+

Requirements for running a code:

+
    +
  1. Compiler (Fastest)
  2. +
  3. Interpreter
  4. +
+

Python:

+
    +
  • Easy typing
  • +
  • Open source
  • +
+

It is dynamically typed Interpreted language.

+

Python versions:
+1. 2.x +2. 3.x

+

Latest: Python 3.9.1 +Preferred 3.8.6

+

Things needed in a program: +1. Input (i/p) +2. Output (o/p) +3. Values +4. Operator

+
Note:
+

[value] - optional parameter

+

Input:

+

Input from the user is obtained using the input statement
+Syntax:

+
input(prompt = "")
+
+

IN [1]

+
# Example 1
+a = input('Enter a number ')
+
+# Example 2
+b = input()
+
+

stdout

+
Enter a number 10
+
+
+

Output:

+

The output is displayed to the user using the print statement
+Syntax:

+
print(values,..., end="\n", sep=" ")
+
+

IN [7]

+
# Example 
+print(a)
+print()
+print(a,b)
+
+

stdout

+
10
+
+10 1
+
+
+

Data in Python

+

Data: Unorderd collection of information

+

Types:

+
    +
  1. Numeric
  2. +
  3. Character
  4. +
  5. Boolean
  6. +
  7. Null
  8. +
  9. Derived or Complex Data Types
  10. +
+

1. Numeric:

+

Associated with number
+Eg: 10, 2.1, -99.7, 3.1416(pi)

+
Types:
+
    +
  1. Integer (int): 10, 100, 0, -5
  2. +
  3. Floating point numbers or double (float): 22/7, -0.15
  4. +
+

2. Character (char):

+

All characters that are defined by Unicode. Look the below chart for the list of characters allowed under ASCII (American Standard Code for Information Interchange) which are most commonly used.

+

+

They are denoted using single quotes (‘’)

+

Eg: ‘1’, ‘a’, ‘#’

+

3. Boolean (bool):

+

Asserts if a condition is True or False +If denotion in Number:
+1. True - number != 0 +2. False - number = 0

+

4. Null or None:

+

If nothing is present

+

Above four primitive data types

+

5. Complex Data Types (Derived):

+

Combination of above four data types

+
Types:
+
    +
  1. List
  2. +
  3. Tuple
  4. +
  5. Set
  6. +
  7. String
  8. +
  9. Dictionary
  10. +
+
String:
+

A collection of characters

+

Eg: ‘Prabhu’, ‘123’, “Hi”, “Hello Python”

+
Additional types in integers (Base):
+
    +
  1. Binary (base 2) [0,1]
  2. +
  3. Octal (base 8) [0-7]
  4. +
  5. Decimal (base 10) [0-9] Most Common
  6. +
  7. HexaDecimal (base 16) [0-9, A-F]
    +The bases allowed are 2 to 35
  8. +
+

Literals

+

Literals are data that are used or processed in a program.

+

Types:

+
    +
  1. Constant - Values that do not change during the execution
  2. +
  3. Variable - Values that change
  4. +
+

There are certain rules to be followed while naming a variable:
+- Should start only with an alphabet or underscore (‘_’) +- Can contain characters defined in ASCII except ( $, &, \, /, etc.) +- It should not be keyword +- No spaces +- Generally, uppercase alphabets are not used in the beginning of a variable name.

+
Naming Conventions:
+

Naming Convention - Wikipedia article
+For Easy readability +- Function or use as name +- first letter in lowercase +- name has Multiple words: + 1. use underscore for space + 2. joint writing with words from second in caps +- No Long names

+

Naming convention for multi word variable names: +1. Camel case (abcAbc) +2. Pascal case (AbcAbc) +3. Screaming case (ABC) +4. Lazy case (abc) +5. Kebab case (ab-ab) +6. Snake case(ab_ab)

+

E.g.: age, input_values, firstName, number, prime_num
+Not: user name, number_to_find_prime

+

IN [3]

+
userName = input()
+user_name = input()
+
+

stdout

+
a
+
+
+

Keywords or Identifiers or Reserved words:

+

Words used for a special purpose in program.

+
Eg: input, print, int, if, for, try, list, etc.
+
+

IN [None]

+
# Key words
+try
+for
+while
+input
+print
+
+

Comments:

+

Lines that are not executed. It used only for understanding by the programmers or users

+

’#’ is used to comment lines

+

Documentation Strings or Doc strings:

+
''' ''' and """ """ define documentation strings.
+
+

Brief explanation of code.

+

IN [1]

+
""" 
+This line gives example of docstrings.
+This doc strings can extend many lines
+"""
+print('Hi')
+
+

stdout

+
Hi
+
+
+

Type Casting and conversion:

+

Convert one form of data into another

+
type() # function gives the data type of a variable
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodResultSyntax
int()Converts Numeric data into integerint(x [, base=10])
float()Converts Numeric Data into floatfloat(x)
str()Converts Data into stringstr([x])
ord()Generates Unicode code point integer value of a characterord(x)
chr()Returns the Unicode character of given valuechr(x)
oct()Returns octal value as a stringoct(x)
bin()Returns Binary value as a stringbin(x)
hex()Returns Hexadecimal value as a stringhex(x)
list()Returns the list form of given iterablelist([x])
tuple()Returns the tuple form of given iterabletuple([x])
set()Returns the set form of given iterableset([x])
dict()Returns Key-value mappingdict([x])
+

IN [10]

+
print(type('123.0'))
+a = float('123.0')
+type(a)
+
+

stdout

+
<class 'str'>
+
+
+

IN [12]

+
print(a)
+int(a)
+
+

stdout

+
123.0
+
+
+

Operators:

+

Used to perform arithmetic and logical operations

+

Types:

+
    +
  1. Arithmetic
  2. +
  3. Relational
  4. +
  5. Assignment
  6. +
  7. Logical
  8. +
  9. Bitwise
  10. +
  11. Membership
  12. +
  13. Identity
  14. +
+
1. Arithmetic:
+

Perform arithmetic operations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorDescriptionExample
$+$Addition2 $+$ 3 = 5
$-$Subtraction2 $-$ 3 = -1
$*$Multiplication2 $*$ 3 = 6
$/$Division2 $/$ 3 = 0.66667
$//$Floor Division (quotient)2 $//$ 3 = 0
%Modulo (returns remainder)2 % 3 = 2
$**$Exponentiation2 $**$ 3 = 8
$+$Unary Plus$+$ 2
$-$Unary Minus$-$3
+
2. Relational:
+

Relations between two variables

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorDescriptionExample
$==$Equala $==$ b
$!=$ or $<>$Not Equala $!=$ b or a $<>$ b
$>$Greatera $>$ b
$>=$Greater or Equala $>=$ b
$<$Lessera $<$ b
$<=$Lesser or Equala $<=$ b
+
3. Assignment:
+

Assigns value to a variable

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorDescriptionExample
$=$Assignc $=$ 30
$+=$Add and assigna $+=$ b
$-=$Subtract and assigna $-=$ b
$*=$Multiply and assigna $*=$ b
$/=$Divide and assigna $/=$ b
$//=$Floor division and assigna $//=$ b
%=Get remainder and assigna %= b
$**=$Exponentiation and assigna $**=$ b
$:=$Walrus operator (to define values from a function)y $:=$ f(x)
+
Note:
+

Walrus operator came into python in version 3.8. It will not work in previous versions.

+
4. Logical:
+

Perform Logical operations

+ + + + + + + + + + + + + + + + + + + + + +
OperatorDescription
andLogical Operator AND
orLogical Operator OR
notLogical operator NOT
+
5. Bitwise:
+

Perform bitwise operations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorDescriptionSyntaxExample
&Bitwise ANDx & y101 & 11
|Bitwise ORx | y101 | 11
~Bitwise NOT~x~1
^Bitwise XORx ^ y1 ^ 1
<<Shifts y bits in x to the left (Left shift operator)x << y111001 << 2
>>Shifts y bits in x to the right (Right Shift Operator)x >> y111001 >> 2
+
6. Membership:
+

Check if an iterable object contains the element

+ + + + + + + + + + + + + + + + + + + + +
OperatorDescriptionSyntax
inTrue if element in iterablex in y
not inTrue if element not in iterablex not in y
+
7. Identity operator:
+

Checks if two operands point to same object

+ + + + + + + + + + + + + + + + + + + + +
OperatorDescriptionSyntax
isTrue if point to same objecta is b
is notTrue if they do not pointa is not b
+

Expressions:

+

A statement that gives a finite value.

+

Types: +1. Infix expressions:
+Example: 12 + 23 +2. Prefix expressions:
+Example: + 12 23 +3. Postfix expressions:
+Example: 12 23 +

+

Escape Sequence:

+

Few special characters defined under ASCII for formatting strings/ output

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SequenceExplanantion
\\Back slash
\‘Apostrophe or Single quotes
\nnew line or line feed
\fform feed
\rcarriage return
\thorizontal tab
\“Double quotes
\0Null character
\abell
\vvertical tab
\u…unicode character
\o…octal values
\x…hexa decimal values
+

String formatting:

+

String formatting or output formatting is an important part of a program output. +The display of output in user understandable form is important.

+

The following are the string formatting methods used (in the order of increasing preference): +1. Simple or no formatting +2. Formatting using format specifiers +3. Formatting using the format() method +4. f-strings

+

1. Simple formtting

+
print('string', variable)
+
+

IN [16]

+
name = input('Enter your name ')
+print('Hello', name,', Welcome')
+
+# Input: Prabhu
+
+

stdout

+
Enter your name  Prabhu
+
+
+

stdout

+
Hello Prabhu , Welcome
+
+
+

2. Format Specifiers:

+

% symbol indicate format specifiers.

+

Types: +1. Integer: %d +2. Float: %f +3. Character: %c +4. String: %s

+
print('string format_specifier'%(order of variables))
+
+

IN [18]

+
name = input()
+# printf("%d", a); in C
+print('Hello %s, Welcome'%(name))
+
+# Input: Sooriya
+
+

stdout

+
 Sooriya
+
+
+

stdout

+
Hello Sooriya, Welcome
+
+
+

IN [20]

+
str1 = 'Python'
+ver = 3.8
+print('Hello %s, Welcome to %s%.1f'%(name, str1, ver))
+print("Welcome to %s%.1f %s"%(str1, ver, name))
+
+

stdout

+
Hello Sooriya, Welcome to Python3.8
+Welcome to Python3.8 Sooriya
+
+
+

3. Format Method:

+

Uses .format() method

+
print("string {order}".format(variables))
+
+

IN [33]

+
print("Hello {}, Welcome".format(name))
+
+

stdout

+
Hello Midhun, Welcome
+
+
+

IN [21]

+
string1 = 'Python'
+print("Hello {0}, Welcome to {2}{1}".format(name, string1, ver))
+print("Hello {}, Welcome to {}".format(name, string1))
+print("Welcome to {}{} {}".format(str1, ver, name))
+
+

stdout

+
Hello Sooriya, Welcome to 3.8Python
+Hello Sooriya, Welcome to Python
+Welcome to Python3.8 Sooriya
+
+
+

4. F-strings:

+

F-strings or formatted strings used to format strings using variables

+
f'string {variable}'
+
+

The f-strings came after Python 3.6

+

IN [22]

+
print(f'Hello {name}, Welcome to {string1}')
+
+

stdout

+
Hello Sooriya, Welcome to Python
+
+
+

IN [26]

+
print(f'Hello {name} '\
+     f'Welocme to {string1}{ver}')
+
+

stdout

+
Hello Sooriya Welocme to Python3.8
+
+
+

Float and integer formatting:

+

The format method is used to format integers and floats as required.

+

Integer Formatting:

+

Leading zeroes adding to integers
+Eg: 01 002

+
1. Format Specifiers:
+
%d - integer  
+%0nd - no. of leading zeroes
+
+

= n - no. of digits in the integer

+
2. format method:
+
format(int_value, format)
+
+
3. f-strings:
+
{int_value:0nd}
+
+

Float formatting:

+

Round off decimal places
+Eg: 10.1234: 10.12

+
1. Format Specifiers:
+
%f - float  
+%.2f - 2 decimal places
+
+
2. format method:
+
format(float_value, format)
+
+
3. f-strings:
+
f"{float_value:.nf}"
+
+

IN [None]

+

+
+

Muliple Assignment in one line:

+

Python allows assignment of different variables in one line.

+

Syntax:

+
var1, var2, var3, ... = val1, val2, val3, ...
+
+

IN [3]

+
a, b, c, d = 10, 20, 30, 40
+print(a)
+print(b)
+print(d)
+print(c)
+
+

stdout

+
10
+20
+40
+30
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/Looping_Statements.html b/docs/Looping_Statements.html new file mode 100644 index 0000000..f10be78 --- /dev/null +++ b/docs/Looping_Statements.html @@ -0,0 +1,420 @@ + + + + + + + + Looping Statements + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Looping Statements

+ +

Execute a group of lines repeatedly.

+

Finite looping is the best practice in programming but infinite looping are done because they are easy at times.

+
    +
  1. For loop
  2. +
  3. While loop
  4. +
+

Looping variables are generally named i, j, and k, while other names can be used.

+

1. For loop:

+

General and most common finite looping.

+

For loop is used to iterate through a sequence or iterator. +Lists, tuple, dictionary and string. +Syntax:

+
for value in iterable:  
+    Statements
+
+

IN [1]

+
# Example 1
+l = [1, 2, 3, 4, 5]
+for i in l:
+    print(i)
+
+

stdout

+
1
+2
+3
+4
+5
+
+
+

IN [2]

+
# Example 2
+s = 'Hello'
+for char in s:
+    print(char)
+
+

stdout

+
H
+e
+l
+l
+o
+
+
+

IN [3]

+
# Error for int
+num = 10
+for i in num:
+    print(num)
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 3, in <module>
+
+    for i in num:
+
+TypeError: 'int' object is not iterable
+
+
+

Range function:

+

Used to create an sequence/object from start to stop in steps

+

Syntax:

+
range(stop)  
+range(start, stop, [step=1])
+
+

IN [5]

+
# Output of range
+print(*range(1, 10))
+print(*range(10))
+
+

stdout

+
1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+
+
+

IN [6]

+
#Example 1
+for i in range(10):
+    print(i)
+
+

stdout

+
0
+1
+2
+3
+4
+5
+6
+7
+8
+9
+
+
+

IN [7]

+
#Example 2
+for i in range(0, 20, 2):
+    print(i)
+
+

stdout

+
0
+2
+4
+6
+8
+10
+12
+14
+16
+18
+
+
+

IN [8]

+
#Example 3
+for i in range(0, 10, 1):
+    print(i)
+
+

stdout

+
0
+1
+2
+3
+4
+5
+6
+7
+8
+9
+
+
+

2. While loops:

+

Most common for infinite looping. +Used to work on numbers or variable length iterables. +Preferred for variable conditions

+

Syntax:

+
while condition:  
+    Statements
+
+

IN [1]

+
# Example 1:
+i = 1
+while i<=10:
+    print(i)
+    i+=1
+
+

stdout

+
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+
+
+

IN [1]

+
# Example 2 using infinite looping
+i = 1
+while True:
+    print(i)
+    if i==100:
+        break
+    i+=1
+
+

stdout

+
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+
+
+

Loop Control statements:

+

Control the execution of the loop

+
    +
  1. Break
  2. +
  3. Continue
  4. +
  5. Pass
  6. +
+

1. break

+

This statement ends the loop when encountered.

+

2. continue

+

Skips the loop execution when encountered.

+

3. pass

+

No change to loop +Used when there no statements currently present

+

IN [2]

+
i = 1
+while i<5:
+    j=0
+    while True:
+        print(i)
+        j+=1 # j = j+1
+        if j==4:
+            break
+    i+=1
+
+

stdout

+
1
+1
+1
+1
+2
+2
+2
+2
+3
+3
+3
+3
+4
+4
+4
+4
+
+
+

IN [3]

+
#Example
+i = 0
+while i<11:
+    i+=1
+    if i==5: continue
+    print(i)
+
+

stdout

+
1
+2
+3
+4
+6
+7
+8
+9
+10
+11
+
+
+

IN [2]

+
#Example 1
+for i in range(10):
+    if i%2 == 0:
+        pass
+    else: print(i)
+
+

stdout

+
1
+3
+5
+7
+9
+
+
+

IN [7]

+
#Example 2
+for i in range (10):
+    if i%2==0: pass
+    else: print('Odd')
+    print(i)
+
+

stdout

+
0
+Odd
+1
+2
+Odd
+3
+4
+Odd
+5
+6
+Odd
+7
+8
+Odd
+9
+
+
+

IN [None]

+

+
+
+ + + + + \ No newline at end of file diff --git a/docs/Modules_and_Packages.html b/docs/Modules_and_Packages.html new file mode 100644 index 0000000..2a85b20 --- /dev/null +++ b/docs/Modules_and_Packages.html @@ -0,0 +1,948 @@ + + + + + + + + Modules and Packages + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Modules and Packages

+ +

Modules are files that contain functions, variables or classes that can be used without redefining them. They’re generally written in Python.

+

Packages are directory or folders which conatin a number of modules or packages in them.

+

Few built-in Modules are: +1. __builtins__ +0. __file__ +2. math +3. cmath +2. sys +4. os +5. itertools +6. string

+

The basics of working with module are discussed using a file prime_generator.py

+

Code:

+
from time import *
+from itertools import *
+from math import *
+
+def prime_gen(n):
+    num = 2
+    while num <= n:
+        k = 2
+        while k * k <= num:
+            if num % k == 0:
+                break
+            k += 1
+        else:
+            yield num
+    num += 1
+
+prime = 2
+prime_square = 4
+__primeval = 3
+
+if __name__ == '__main__':
+    t = time()
+    for i in prime_gen(10 ** 2):
+        print(i)
+    print(time()-t)
+
+

Contents: +1. prime_gen - function or generator +2. prime - varaiable (constant when imported) +3. prime_square - variable (constant when imported) +4. __primeval - private value

+

import statement:

+

The import keyword is used to import a module or package.

+

Syntax:

+
import module_name
+
+

IN [1]

+
import prime_generator
+
+for i in prime_generator.prime_gen(20):
+    print(i, end=' ')
+
+

stdout

+
2 3 5 7 11 13 17 19 
+
+

from statement:

+

The from keyword is used to import a specific set of functions or classes from a module.

+

Syntax:

+
from module_name import function_name
+
+

IN [2]

+
from prime_generator import prime_gen
+
+for i in prime_gen(20):
+    print(i, end=' ')
+
+

stdout

+
2 3 5 7 11 13 17 19 
+
+

Importing all the objects from the module:

+

To import all the functions or objects, use * .

+

Syntax:

+
from module_name import *
+
+

IN [3]

+
from prime_generator import *
+
+for i in prime_gen(20):
+    print(i, end=' ')
+
+

stdout

+
2 3 5 7 11 13 17 19 
+
+

as Keyword:

+

as Keyword is used to have a custom name for imported module or function.

+

Syntax:

+
import moule_name as custom_name
+from module_name import function_name as custom_name
+
+

IN [4]

+
import prime_generator as pg
+
+for i in pg.prime_gen(20):
+    print(i, end=' ')
+
+

stdout

+
2 3 5 7 11 13 17 19 
+
+

IN [6]

+
from prime_generator import prime_gen as pgf
+
+for i in pgf(20):
+    print(i, end=' ')
+
+

stdout

+
2 3 5 7 11 13 17 19 
+
+

__name__:

+

It returns the name of the module without the extension. If called for main executing program (main module), it returns ‘__main__‘

+

Syntax:

+
module_name.__name__
+
+

IN [8]

+
import prime_generator as pg
+
+print(pg.__name__)
+print(__name__)
+
+

stdout

+
prime_generator
+__main__
+
+
+

dir method:

+

Returns the list of attributes (that are relevant) of an object or a module. By default, it gives the details of main module.

+

Syntax:

+
dir([object])
+
+

IN [1]

+
import prime_generator
+
+print(dir(prime_generator))
+print()
+print(dir(prime_generator.prime_gen))
+print()
+print(dir())
+
+

stdout

+
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__primeval', '__spec__', 'accumulate', 'acos', 'acosh', 'altzone', 'asctime', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'chain', 'comb', 'combinations', 'combinations_with_replacement', 'compress', 'copysign', 'cos', 'cosh', 'count', 'ctime', 'cycle', 'daylight', 'degrees', 'dist', 'dropwhile', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'filterfalse', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'get_clock_info', 'gmtime', 'groupby', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'islice', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'localtime', 'log', 'log10', 'log1p', 'log2', 'mktime', 'modf', 'monotonic', 'monotonic_ns', 'nan', 'nextafter', 'perf_counter', 'perf_counter_ns', 'perm', 'permutations', 'pi', 'pow', 'prime', 'prime_gen', 'prime_square', 'process_time', 'process_time_ns', 'prod', 'product', 'radians', 'remainder', 'repeat', 'sin', 'sinh', 'sleep', 'sqrt', 'starmap', 'strftime', 'strptime', 'struct_time', 'takewhile', 'tan', 'tanh', 'tau', 'tee', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'trunc', 'tzname', 'ulp', 'zip_longest']
+
+['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
+
+['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'prime_generator', 'quit']
+
+
+

namespace:

+

A container that has a list of names (objects) defined in a module. It is the place where python searches for objects defined and used in a function.

+

Global, Local and Built-in Namespaces

+

Global:

+

Namespace containing values defined throughout a file or module (globally)

+

Local:

+

Namespace containing values defined in a part of a file or module (Locally)

+

Builtin:

+

Namespace containing values common for all python file.

+

Order of Search:

+
    +
  1. Local
  2. +
  3. Global
  4. +
  5. Builtin
  6. +
+

Packages:

+

Directory or folder containing a number of modules and subpackages.

+

It contains ‘__init__.py’ file which defines the modules that can be imported from the package.

+

Importing a module from package:

+
import package_name.module_name
+import package_name.module_name as custom_name
+
+

Import a specific object from a module:

+
from package_name.module_name import object_name
+
+

Builtins:

+

__builtins__ module contains the list of methods and variables that are standard definitions in Python.

+

IN [8]

+
builtin = dir(__builtins__)
+for i in builtin:
+    print(i)
+
+

stdout

+
ArithmeticError
+AssertionError
+AttributeError
+BaseException
+BlockingIOError
+BrokenPipeError
+BufferError
+BytesWarning
+ChildProcessError
+ConnectionAbortedError
+ConnectionError
+ConnectionRefusedError
+ConnectionResetError
+DeprecationWarning
+EOFError
+Ellipsis
+EnvironmentError
+Exception
+False
+FileExistsError
+FileNotFoundError
+FloatingPointError
+FutureWarning
+GeneratorExit
+IOError
+ImportError
+ImportWarning
+IndentationError
+IndexError
+InterruptedError
+IsADirectoryError
+KeyError
+KeyboardInterrupt
+LookupError
+MemoryError
+ModuleNotFoundError
+NameError
+None
+NotADirectoryError
+NotImplemented
+NotImplementedError
+OSError
+OverflowError
+PendingDeprecationWarning
+PermissionError
+ProcessLookupError
+RecursionError
+ReferenceError
+ResourceWarning
+RuntimeError
+RuntimeWarning
+StopAsyncIteration
+StopIteration
+SyntaxError
+SyntaxWarning
+SystemError
+SystemExit
+TabError
+TimeoutError
+True
+TypeError
+UnboundLocalError
+UnicodeDecodeError
+UnicodeEncodeError
+UnicodeError
+UnicodeTranslateError
+UnicodeWarning
+UserWarning
+ValueError
+Warning
+WindowsError
+ZeroDivisionError
+__IPYTHON__
+__build_class__
+__debug__
+__doc__
+__import__
+__loader__
+__name__
+__package__
+__spec__
+abs
+all
+any
+ascii
+bin
+bool
+breakpoint
+bytearray
+bytes
+callable
+chr
+classmethod
+compile
+complex
+copyright
+credits
+delattr
+dict
+dir
+display
+divmod
+enumerate
+eval
+exec
+filter
+float
+format
+frozenset
+get_ipython
+getattr
+globals
+hasattr
+hash
+help
+hex
+id
+input
+int
+isinstance
+issubclass
+iter
+len
+license
+list
+locals
+map
+max
+memoryview
+min
+next
+object
+oct
+open
+ord
+pow
+print
+property
+range
+repr
+reversed
+round
+set
+setattr
+slice
+sorted
+staticmethod
+str
+sum
+super
+tuple
+type
+vars
+zip
+
+
+

__file__ module:

+

It contains the list of builtin variables and functions that can be used in the current file.

+

contents:

+

__add__
+__class__
+__contains__
+__delattr__
+__dir__
+__doc__
+__eq__
+__format__
+__ge__
+__getattribute__
+__getitem__
+__getnewargs__
+__gt__
+__hash__
+__init__
+__init_subclass__
+__iter__
+__le__
+__len__
+__lt__
+__mod__
+__mul__
+__ne__
+__new__
+__reduce__
+__reduce_ex__
+__repr__
+__rmod__
+__rmul__
+__setattr__
+__sizeof__
+__str__
+__subclasshook__
+capitalize
+casefold
+center
+count
+encode
+endswith
+expandtabs
+find
+format
+format_map
+index
+isalnum
+isalpha
+isascii
+isdecimal
+isdigit
+isidentifier
+islower
+isnumeric
+isprintable
+isspace
+istitle
+isupper
+join
+ljust
+lower
+lstrip
+maketrans
+partition
+replace
+rfind
+rindex
+rjust
+rpartition
+rsplit
+rstrip
+split
+splitlines
+startswith
+strip
+swapcase
+title
+translate
+upper
+zfill

+

Private in modules:

+

Objects can be restricted to usage when running as a main module. They cannot be imported when importing the complete module using ‘ * ‘.

+

They start and end with double underscores, __

+

IN [2]

+
import prime_generator as pg
+
+print(pg.__primeval)
+
+

stdout

+
3
+
+
+

IN [3]

+
from prime_generator import *
+
+print(__primeval)
+
+

Error

+

+Traceback (most recent call last):
+
+  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 3, in <module>
+
+    print(__primeval)
+
+NameError: name '__primeval' is not defined
+
+
+

globals(), locals() and reload()

+

globals - returns the list of objects that can be accessed globally from that point.

+

locals - returns the list of objects that can be accessed locally from that point.

+

reload - reloads the given module. (imported from impotlib module)

+

Syntax:

+
reload(module_name)
+
+

math:

+

This module contains list of all mathematical functions.

+

IN [3]

+
import math
+
+print(*dir(math), sep='\n')
+
+

stdout

+
__doc__
+__loader__
+__name__
+__package__
+__spec__
+acos
+acosh
+asin
+asinh
+atan
+atan2
+atanh
+ceil
+comb
+copysign
+cos
+cosh
+degrees
+dist
+e
+erf
+erfc
+exp
+expm1
+fabs
+factorial
+floor
+fmod
+frexp
+fsum
+gamma
+gcd
+hypot
+inf
+isclose
+isfinite
+isinf
+isnan
+isqrt
+ldexp
+lgamma
+log
+log10
+log1p
+log2
+modf
+nan
+perm
+pi
+pow
+prod
+radians
+remainder
+sin
+sinh
+sqrt
+tan
+tanh
+tau
+trunc
+
+
+

IN [5]

+
import math
+
+print(math.pi/2)
+print(math.asin(1))
+# 1.570796... = pi/2
+
+

stdout

+
1.5707963267948966
+1.5707963267948966
+
+
+

IN [6]

+
# 21.33 ceil - 22
+# 21.33 floor - 21
+# 21, 21.33, 22
+print(math.ceil(21.33))
+print(math.floor(21.33))
+
+

stdout

+
22
+21
+
+
+

IN [10]

+
math.pow(2, 3) # 2 ** 3
+
+

$\mathit{^5P_2}$

+

IN [11]

+
math.perm(5, 2) # 5P2
+
+

$\mathit{^5C_2}$

+

IN [12]

+
math.comb(5, 2) # 5C2
+
+

cmath:

+

Like math, used to work with complex numbers.

+

IN [1]

+
import cmath
+
+print(*dir(cmath), sep='\n')
+
+

stdout

+
__doc__
+__loader__
+__name__
+__package__
+__spec__
+acos
+acosh
+asin
+asinh
+atan
+atanh
+cos
+cosh
+e
+exp
+inf
+infj
+isclose
+isfinite
+isinf
+isnan
+log
+log10
+nan
+nanj
+phase
+pi
+polar
+rect
+sin
+sinh
+sqrt
+tan
+tanh
+tau
+
+
+

sys:

+

Work with program execution and system.

+

IN [2]

+
import sys
+
+print(*dir(sys), sep='\n')
+
+

stdout

+
__breakpointhook__
+__displayhook__
+__doc__
+__excepthook__
+__interactivehook__
+__loader__
+__name__
+__package__
+__spec__
+__stderr__
+__stdin__
+__stdout__
+__unraisablehook__
+_base_executable
+_clear_type_cache
+_current_frames
+_debugmallocstats
+_enablelegacywindowsfsencoding
+_framework
+_getframe
+_git
+_home
+_xoptions
+addaudithook
+api_version
+argv
+audit
+base_exec_prefix
+base_prefix
+breakpointhook
+builtin_module_names
+byteorder
+call_tracing
+callstats
+copyright
+displayhook
+dllhandle
+dont_write_bytecode
+exc_info
+excepthook
+exec_prefix
+executable
+exit
+flags
+float_info
+float_repr_style
+get_asyncgen_hooks
+get_coroutine_origin_tracking_depth
+getallocatedblocks
+getcheckinterval
+getdefaultencoding
+getfilesystemencodeerrors
+getfilesystemencoding
+getprofile
+getrecursionlimit
+getrefcount
+getsizeof
+getswitchinterval
+gettrace
+getwindowsversion
+hash_info
+hexversion
+implementation
+int_info
+intern
+is_finalizing
+maxsize
+maxunicode
+meta_path
+modules
+path
+path_hooks
+path_importer_cache
+platform
+prefix
+ps1
+ps2
+ps3
+pycache_prefix
+set_asyncgen_hooks
+set_coroutine_origin_tracking_depth
+setcheckinterval
+setprofile
+setrecursionlimit
+setswitchinterval
+settrace
+stderr
+stdin
+stdout
+thread_info
+unraisablehook
+version
+version_info
+warnoptions
+winver
+
+
+

os:

+

works with operating system

+

IN [3]

+
import os
+print(*dir(os), sep='\n')
+
+

stdout

+
DirEntry
+F_OK
+MutableMapping
+O_APPEND
+O_BINARY
+O_CREAT
+O_EXCL
+O_NOINHERIT
+O_RANDOM
+O_RDONLY
+O_RDWR
+O_SEQUENTIAL
+O_SHORT_LIVED
+O_TEMPORARY
+O_TEXT
+O_TRUNC
+O_WRONLY
+P_DETACH
+P_NOWAIT
+P_NOWAITO
+P_OVERLAY
+P_WAIT
+PathLike
+R_OK
+SEEK_CUR
+SEEK_END
+SEEK_SET
+TMP_MAX
+W_OK
+X_OK
+_AddedDllDirectory
+_Environ
+__all__
+__builtins__
+__cached__
+__doc__
+__file__
+__loader__
+__name__
+__package__
+__spec__
+_check_methods
+_execvpe
+_exists
+_exit
+_fspath
+_get_exports_list
+_putenv
+_unsetenv
+_wrap_close
+abc
+abort
+access
+add_dll_directory
+altsep
+chdir
+chmod
+close
+closerange
+cpu_count
+curdir
+defpath
+device_encoding
+devnull
+dup
+dup2
+environ
+error
+execl
+execle
+execlp
+execlpe
+execv
+execve
+execvp
+execvpe
+extsep
+fdopen
+fsdecode
+fsencode
+fspath
+fstat
+fsync
+ftruncate
+get_exec_path
+get_handle_inheritable
+get_inheritable
+get_terminal_size
+getcwd
+getcwdb
+getenv
+getlogin
+getpid
+getppid
+isatty
+kill
+linesep
+link
+listdir
+lseek
+lstat
+makedirs
+mkdir
+name
+open
+pardir
+path
+pathsep
+pipe
+popen
+putenv
+read
+readlink
+remove
+removedirs
+rename
+renames
+replace
+rmdir
+scandir
+sep
+set_handle_inheritable
+set_inheritable
+spawnl
+spawnle
+spawnv
+spawnve
+st
+startfile
+stat
+stat_result
+statvfs_result
+strerror
+supports_bytes_environ
+supports_dir_fd
+supports_effective_ids
+supports_fd
+supports_follow_symlinks
+symlink
+sys
+system
+terminal_size
+times
+times_result
+truncate
+umask
+uname_result
+unlink
+urandom
+utime
+waitpid
+walk
+write
+
+
+

itertools:

+

A module containing iterators for efficient looping

+

IN [4]

+
import itertools
+
+print(*dir(itertools), sep='\n')
+
+

stdout

+
__doc__
+__loader__
+__name__
+__package__
+__spec__
+_grouper
+_tee
+_tee_dataobject
+accumulate
+chain
+combinations
+combinations_with_replacement
+compress
+count
+cycle
+dropwhile
+filterfalse
+groupby
+islice
+permutations
+product
+repeat
+starmap
+takewhile
+tee
+zip_longest
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/OOPS.html b/docs/OOPS.html new file mode 100644 index 0000000..efdb022 --- /dev/null +++ b/docs/OOPS.html @@ -0,0 +1,266 @@ + + + + + + + + Object Oriented Programming - Part 1 + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Object Oriented Programming - Part 1

+ +

OOP

+

Object Oriented Programming or OOP is working with classes and objects. It involves interaction between objects having various attributes.

+

Python is a object oriented programming language. This means that all the types are representation or instance of a type class.

+

Components

+
    +
  1. Class
  2. +
  3. Object
  4. +
+

Class

+

It is a structure, a blueprint or a building block (a code block) representing or defining the attributes (features and behaviour) of similar parameters.

+

Definition

+

Using class keyword. +Name of a class should start with an uppercase letter.

+

Syntax:

+
class Class_name
+
+

IN [1]

+
class Students:
+    roll_no = int()
+    name = str()
+
+

Object

+

It is an instance of a class.

+

Syntax:

+
obj_name = Class_name()
+
+

IN [2]

+
student1 = Students() # creating a new object
+
+student1.roll_no = 1
+student1.name = 'Prabhu'
+
+

IN [3]

+
print(student1.name)
+print(student1.roll_no)
+
+

stdout

+
Prabhu
+1
+
+
+

self Keyword

+

Calls the attributes for current instance or object.

+

Syntax:

+
self.attribute_name
+
+

Defining attributes and behavior in a class

+

An object is generally defined by the follwing:

+
    +
  1. Fields (variables) or Attributes
  2. +
  3. Methods (functions) or Behavior
  4. +
+

Fields

+

The fields are the variables or containers that store data used and related to an object/Class

+

Types:

+
    +
  1. Instance fields
  2. +
  3. Class or static fields
  4. +
+

Instance fields

+

The instance fields are variables that are associated with an object, an instance of the class.

+

The data they have may vary from object to object and are independent. The field of one instance cannot be accessed by the other.
+The instance variables are accessed as follows:

+
# Inside the class using `self` keyword
+self.instance_variable
+
+# Outside the class using the object name
+object_name.instance_variable
+
+

Class fields

+

The class variables are variables that are common throughout the instances of the defined class and can be accessed by all of them.

+

Modifying data in one object changes it for all the present instances.
+They are accessed inside and outside the class definition as follows:

+
# Using class name to access static variables
+Class_name.class_variable
+
+

IN [1]

+
class Student_details:
+    student_count = 0
+    def __init__(self, name):
+        self.name = name # Instance variable
+        Student_details.student_count += 1 # Class Variable
+
+s = Student_details("Prabhu")
+print(s.name) # Instance variable
+s1 = Student_details("Mano")
+print(s1.name) # Instance variable
+print(Student_details.student_count) # Class variable
+
+

stdout

+
Prabhu
+Mano
+2
+
+
+

Methods

+

The methods are block of code that, like functions, execute a specific task

+

Though a method and function are defined in the same way, they have differences.

+

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

+

A method is a piece of code that is called by a name that is associated with an object.

+

In most respects it is identical to a function except for two key differences:

+
    +
  1. A method is implicitly passed the object on which it was called.
  2. +
  3. A method is able to operate on data that is contained within the class
  4. +
+

(remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

+

Source: What’s the difference between a method and a function? - StackOverflow

+

Types:

+
    +
  1. Instance methods
  2. +
  3. Static methods
  4. +
+

Instance methods

+

Instance methods are methods/behavior that are associated with objects. When an object calls one of its instnace methods, the instance method gets implicitly passed object and uses the data it gets with other required parameters to do the task.
+Definition and access:

+
# Definition
+def instance_method(self[, ...]): # the self keyword indicates the implicit passing of the object
+    # Statements
+
+# access inside the class (in another instance method)
+self.instance_method(...)
+
+# Access outside the class
+obj.instance_method(...)
+
+

Note: It is to be noted that an instance method can be called only inside another instance method

+

Static or Class method

+

A static method is a method that is common for all objects. It is equivalent of function being defined outside the class.

+

A static method is identified by the decorator @staticmethod and has implicit object passing using self keyword.

+

Definition and Access:

+
@staticmethod
+def class_method([...]):
+    #Statement(s)
+
+# accessing the method using class name
+Class_name.class_method([...])
+
+

The static method can be called inside another static method or instance method(s)

+

Constructor

+

A method that executes a set of code whenever a new object/instance is created.

+

Defined as __new__(). Generally, this is not defined/overridden and follows the default definition as in the object class

+
def __new__(cls, *args, **kwargs):
+    # Custom constructor
+
+

Initializer

+

An instance method that initializes the object (instance) created by call with the parameters passed.

+

The __new__() method calls this automatically.

+

Defined as __init__().

+
def __init__(self, *args, **kwargs):
+    # Statements for object Initialization
+
+

IN [7]

+
class Student:
+    def __init__(self): # default constructor
+        self.roll_no = 0
+        self.name = 'Name'
+#         print('__init__ file')
+
+    def study(self):
+        print('Studying....')
+
+

IN [8]

+
st1 = Student()
+st1.roll_no = 1
+st1.name = 'Ravi'
+print(f'Roll No: {st1.roll_no}, Name: {st1.name}')
+
+

stdout

+
__init__ file
+Roll No: 1, Name: Ravi
+
+
+

IN [2]

+
class Student_details:
+    def __init__(self, rn = 0, st_name = 'Name'): # Parametric Constructor
+        self.roll_no = rn
+        self.name = st_name
+        # print('__init__ file')
+
+    def study(self):
+        print('Studying....')
+    @staticmethod
+    def work():
+        print("Working...")
+
+

IN [3]

+
st2 = Student_details(2, 'Rahul')
+print(f'Roll No: {st2.roll_no}, Name: {st2.name}')
+Student_details.work()
+
+

stdout

+
Roll No: 2, Name: Rahul
+Working...
+
+
+

destructor

+

Delete the current instance of class or object. It has default definition in the object Base class

+

Use __del__() method to override it

+
def __del__(self, *args, **kwargs):
+    # Custom destructor
+
+

Some other methods

+
    +
  1. __repr__ - String representation
  2. +
  3. __cmp__ - Compare two objects
  4. +
  5. __len__ - length of object
  6. +
  7. __lt__ - less than
  8. +
  9. __le__ - less than or equal
  10. +
  11. __gt__ - greater than
  12. +
  13. __ge__ - greater than or equal
  14. +
  15. __ne__ - not equal
  16. +
  17. __eq__ - equal
  18. +
  19. __getitem__ - get a key from a iterable
  20. +
  21. __setitem__ - set a value to the given key of iterable
  22. +
+

Private variables and methods

+

Start with __

+

E.g.: __var, __method

+

It is advised for best programming practice to avoid calling private attributes outside the class.
+But if needed, use the following syntax:

+
obj._classname__attribute
+
+

Check the complete example OOPS.py

+

Ignore the imports. They have been used to provide hinting about the types of each variable

+
+ + + + + \ No newline at end of file diff --git a/docs/OOPS.py b/docs/OOPS.py new file mode 100644 index 0000000..c9a8d4a --- /dev/null +++ b/docs/OOPS.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import Any, Literal, Union + + +class Student(object): + student_count: int = 0 + stud_list: dict[int, str] = dict() + __roll_no: int = 0 + name: str + club: list[Any] + + def __new__(cls, rn: int = 0, st_name: str = "Name", *clubs: Any) -> Student: + print("__new__ magic method is called to create an obj\n") + inst: Student = super().__new__(cls) + return inst + + # Parametric Constructor + def __init__(self, rn: int = 0, st_name: str = "Name", *clubs: Any) -> None: + Student.student_count += 1 + self._roll_no = rn + self.name = st_name + self.club = list(clubs) + Student.stud_list[rn] = st_name + # {_roll_no: st_name} + + def study(self) -> None: + print(f"{self.name} is Studying....") + + @staticmethod + def wake() -> str: + # self.study() + return "Woke" + + # destructor + def __del__(self) -> None: + Student.student_count -= 1 + Student.stud_list.pop(self._roll_no) + + # String representation of Object + def __repr__(self) -> str: + return f"Roll no.: {self._roll_no} \nName: {self.name}\n" f"Clubs: {self.club}" + + # Less than + def __lt__(self, obj: Student) -> bool: + return self.name < obj.name + + # Less than or equal + def __le__(self, obj: Student) -> bool: + return self.name <= obj.name + + # Greater than + def __gt__(self, obj: Student) -> bool: + return self.name > obj.name + + # Greater than or equal + def __ge__(self, obj: Student) -> bool: + return self.name >= obj.name + + # Not equal + def __ne__(self, obj: Student) -> bool: + return self.name != obj.name + + # Equal + def __eq__(self, obj: Student) -> bool: + return self.name == obj.name + + def __getitem__(self, key: int) -> str: + return self.club[key - 1] + + def __setitem__(self, key: int, value: Union[str, Literal]) -> None: + self.club[key - 1] = value + + def __len__(self) -> int: + return len(self.club) + + # getter + @property + def _roll_no(self) -> int: + # print('Getter called') + return self.__roll_no + + # setter + @_roll_no.setter + def _roll_no(self, rn: int) -> None: + # print('Setter called') + if self._roll_no in Student.stud_list.keys(): + Student.stud_list.pop(self.__roll_no) + Student.stud_list[rn] = self.name + self.__roll_no = rn + + +# Object 1 +st1 = Student(1, "Prabhu", "Coding Club", "Robotics Club") +print(st1) + +print(Student.student_count) +print(Student.stud_list, "\n") + +st1[2] = "Envy Club" +print(st1) + +st2 = Student(3, "Mano", "Coding Club", "Cyber club") +print("\n", st2, "\n", sep="") +print(Student.student_count) +print(Student.stud_list, "\n") + +st2._roll_no = 2 + +print("\n", Student.student_count, sep="") +print(Student.stud_list, "\n") + +del st2 + +print("\n", Student.student_count) +print(Student.stud_list, "\n") diff --git a/docs/Practice_code1.html b/docs/Practice_code1.html new file mode 100644 index 0000000..704be46 --- /dev/null +++ b/docs/Practice_code1.html @@ -0,0 +1,376 @@ + + + + + + + + Input/Output Practice questions + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Input/Output Practice questions

+

This file contains practice question for Introduction to Python programming (input ad output)

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+
+

Q1: Write a program to print ‘Hello World’

+
+

Q2: Write a program to get Name from the user and print it.

+
+

Sample 1:
+I/p: Chandru
+O/p: Chandru

+
+


+
+

Sample 2:
+I/p: Prabhu
+O/p: Prabhu

+
+
+

Q3: Write a program to get Name and age from user and print it.

+
+

Sample 1:
+I/p:
+Chandru 19
+O/p:
+Chandru
+19

+
+


+
+

Sample 2:
+I/p:
+Prabhu 20
+O/p:
+Prabhu
+20

+
+
+

Q4: Write a program to get two numbers from user and print their sum

+
+

Sample 1:
+I/p:
+12
+12
+O/p:
+24

+
+


+
+

Sample 2:
+I/p:
+10
+15
+O/p:
+25

+
+
+

Q5: Write a program to get two numbers and perform all arithmetic operations on them.

+
+

Q6: (Update of Q4)
+Print formatted output

+
+

Sample 1:
+I/p:
+12
+12
+O/p:
+Sum of 12 and 12 is 24

+
+


+
+

Sample 2:
+I/p:
+10
+15
+O/p:
+Sum of 10 and 15 is 25

+
+
+

Q6: (Update of Q4)
+Print formatted output

+
+

Sample 1:
+I/p:
+12
+12
+O/p:
+Sum of 12 and 12 is 24

+
+


+
+

Sample 2:
+I/p:
+10
+15
+O/p:
+Sum of 10 and 15 is 25

+
+
+

Q7: Write a program to get name from the user and wish them Good Morning

+
+

Sample:
+I/p: Jenyhin
+O/p: Good Morning, Jenyhin

+
+
+

Q8: Write a program to get the side of the square and print its perimeter
+$\text{Perimeter of a square} = 4 \times \rm{side}$

+
+

Sample 1:
+I/p: 4
+O/p: 16

+
+


+
+

Sample 2:
+I/p: 22
+O/p: 88

+
+
+

Q9: Write a program to get the side of the square and print its area
+$\text{Area of square} = \rm{side} \times \rm{side}$

+
+

Sample 1:
+I/p: 4
+O/p: 16

+
+


+
+

Sample 2:
+I/p: 22
+O/p: 484

+
+
+

Q10: Write a program to get the length and breadth of a rectangle and print its perimeter
+$\text{Perimeter of a rectangle} = 2 \times \rm{(length + breadth)}$

+
+

Sample 1:
+I/p:
+4
+4
+O/p: 16

+
+


+
+

Sample 2:
+I/p:
+22
+21
+O/p: 86

+
+
+

Q11: Write a program to get the length and breadth of a rectangle and print its area
+$\text{Area of a rectangle} = \text{length} \times \text{breadth}$

+
+

Sample 1:
+I/p:
+4
+4
+O/p: 16

+
+


+
+

Sample 2:
+I/p:
+22
+21
+O/p: 462

+
+
+

Q12: Write a program to get the number of sides and length of each side of a regular polygon and print its perimeter.
+$\text{Perimeter} = \text{number of sides} \times \text{length of one side}$

+
+

Sample 1:
+I/p:
+8
+4
+O/p: 32

+
+


+
+

Sample 2:
+I/p:
+7
+21
+O/p: 147

+
+
+

Q13: Write a program to get the length and height of a right triangle and print its area.
+$\text{Area of right triangle} = \dfrac{1}{2} \times \rm{base} \times \rm{height}$

+
+

Sample 1:
+I/p:
+4
+4
+O/p: 8.0

+
+


+
+

Sample 2:
+I/p:
+22
+21
+O/p: 231.0

+
+
+

Q14: Write a program to get the radius of a circle and print its perimeter rounded off to 3 decimal places. (Take $\pi = 3.14159$)
+$\text{Perimeter of a circle} = 2\pi \times \rm{radius}$

+
+

Sample 1:
+I/p:
+4
+O/p: 25.133

+
+


+
+

Sample 2:
+I/p:
+22
+O/p: 138.230

+
+
+

Q15: Write a program to get the radius of a circle and print its area rounded off to 3 decimal places. (Take $\pi = 3.14159$)
+$\text{Area of a circle} = \pi \times \rm{radius}^2$

+
+

Sample 1:
+I/p:
+4
+O/p: 50.265

+

Sample 2:
+I/p:
+21
+O/p: 1385.442

+
+
+

Q16: Write a program to get the sides of a triangle and print its area using Heron’s Formula rounded off to 3 decimal places.
+$\text{Area of right triangle} = \sqrt{s \times (s-a)\times(s-b)\times(s-c)}$
+$\rm{where},$
+$s = \text{Semi-Perimeter} = \dfrac{\text{Perimter of triangle}}{2}$
+$a, ~b, ~c = \text{Sides of the triangle}$

+
+

Sample 1:
+I/p:
+3
+4
+5
+O/p: 6.0

+

Sample 2:
+I/p:
+12
+21
+30
+O/p: 98.359

+
+
+

Q17: Write a program to get the side of a equilateral triangle and print its area rounded off to 4 decimal places.
+$\text{Area of equilateral triangle} = \dfrac{\sqrt{3}}{4} \times \rm{side}^2$

+
+

Sample 1:
+I/p:
+4
+O/p: 6.9282

+
+


+
+

Sample 2:
+I/p:
+31
+O/p: 416.1252

+
+
+

Q18: Write a program to get the length and height of a right triangle and print the length of its hypotenuse rounded off to 3 decimal places using Pythagoras Theorem.
+From Pythagoras theorem, $ \rm{hypotenuse} = \sqrt{\rm{base}^2 + \rm{height}^2}$

+
+

Sample 1:
+I/p:
+3
+4
+O/p: 5

+
+


+
+

Sample 2:
+I/p:
+12
+6
+O/p: 13.416

+
+
+

Q19: Write a program to get the side of a cube and print its volume.
+$\text{Volume of cube} = \rm{side}^3$

+
+

Sample 1:
+I/P: 15
+O/P: 3375

+
+
+

Q20: Write a program to get the side of a cube and print its total surface area.
+$ \text{T.S.A of Cube} = 6 \times \rm{side}^2$

+
+

Sample 1:
+I/P: 15
+O/P: 1350

+
+
+

Q21: Write a program to get the side of a cube and print its Lateral surface area.
+$\text{L.S.A of cube} = 4 \times \rm{side}^2$

+
+

Q22: Write a program to get the length, breadth and height of a cuboid and print its volume.
+$\text{Volume of Cuboid} = \rm{length} \times \rm{breadth} \times \rm{height}$

+
+

Sample 1:
+I/P:
+43
+28
+35
+O/P: 42140

+
+
+

Q23: Write a program to get the length, breadth and height of a cuboid and print its Total Surface Area.
+$\text{T.S.A of Cuboid} = 2 \times ( (\rm{length} \times \rm{breadth}) + (\rm{breadth} \times \rm{height}) + (\rm{height} \times \rm{length}))$

+
+

Sample 1:
+I/P:
+43
+28
+35
+O/P: 7378

+
+
+

Q24: Write a program to get the length, breadth and height of a cuboid and print its Lateral Surface Area.
+$\text{L.S.A of Cuboid} = 2 \times \rm{height} \times (\rm{breadth}+ \rm{length})$

+
+

Check Solution

+
+ + + + + \ No newline at end of file diff --git a/docs/Practice_code2.html b/docs/Practice_code2.html new file mode 100644 index 0000000..a60dc5c --- /dev/null +++ b/docs/Practice_code2.html @@ -0,0 +1,138 @@ + + + + + + + + Condition Statements practice + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Condition Statements practice

+

This Notebook Contains practice question for the note on Condition statements.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+
+

Q1: Write a program to get a number as input and print if it is odd or even.

+
+

Sample 1:
+I/P: 10
+O/P: Even

+
+


+
+

Sample 2:
+I/P: 11
+O/P: Odd

+
+
+

Q2: Write a program to get a number as input and check whether it is positive, negative or zero.

+
+

Sample 1:
+I/P: 10
+O/P: Positive

+
+


+
+

Sample 2:
+I/P: 0
+O/P: Zero

+
+


+
+

Sample 3:
+I/P: -5
+O/P: Negative

+
+
+

Q3: Write a program to get the mark of a student as input print his grade.

+

Condition:

+
mark < 0 or mark > 100: Invalid
+90 < mark <= 100: O
+80 < mark <= 90 : A+
+70 < mark <= 80 : A
+60 < mark <= 70 : B+
+50 <= mark <= 60: B
+ 0 <= mark < 50: Fail
+
+
+

Sample 1:
+I/P: 85
+O/P: A+

+
+


+
+

Sample 2:
+I/P: 10
+O/P: Fail

+
+
+

Q4: Write a program to get the age of the user and print if he is eligible to vote.

+

Condition: +A person is eligible to vote if his/her age is greater than or equal to 18

+
+

Sample 1:
+I/P: 10
+O/P: Ineligible

+
+


+
+

Sample 2:
+I/P: 27
+O/P: Eligible

+
+
+

Q5: Code a simple Calculator.

+
+

Q6: Write a program to get an input from the user and print if it is a vowel or a consonant.

+
+

Q7: Write a program to two numbers and print the greatest of them.

+
+

Q8: Write a program to get three numbers and the print the greatest of them.

+
+

Q9: Write a program to check if a number is a perfect square or not.

+
+

Q10: The humidity (in percentage) and temperature (in celsius) value in a city is given as the input to the program. The program must print YES as the output if there is a possibility of rain. Else the program must print NO as the output. If one of the conditions given below is true then there is a possibility of rain.

+

Condition:

+
    +
  1. Humidity > 90
  2. +
  3. Temperature < 18
  4. +
  5. Humidity > 70 and Temperature < 30
  6. +
  7. Humidity > 60 and Temperature < 24
  8. +
+
+

Q11: Write a program to get a year as input and print if it is a leap year or not.
+A year is leap if it is either divisible 4 or 400 and not 100.

+
+

Check Solution

+
+ + + + + \ No newline at end of file diff --git a/docs/Practice_code3.html b/docs/Practice_code3.html new file mode 100644 index 0000000..7679504 --- /dev/null +++ b/docs/Practice_code3.html @@ -0,0 +1,139 @@ + + + + + + + + Looping Practice + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Looping Practice

+

This Notebook Contains practice question for the note on Looping Statements.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+
+

Q1: Write a program to get the value of n from the user and print sum of n natural numbers as output.

+
+

Q2: Write a program to get the values of n and n numbers from the user and print sum of the n numbers as output.
+Input:

+

First line contains the number n
+Next n lines contain n integers

+

Output: +Sum of n numbers

+
+

Sample 1:
+I/P:
+10
+1
+5
+7
+22
+20
+40
+2
+53
+18
+-1
+O/p: 167

+
+
+

Q3: Write a program get a number from user and print if it is prime or composite.

+
+

Q4: Write a program to get a number from the user and print its factorial as output.

+
+

Q5: Write a program to get the value of n from the user and print the first n terms of the Fibonacci series as output.

+
+

Q6: Write a program to get a number n from the user and print its reverse as output.

+
+

Q7: Write a program to get a number and check if it is an armstrong number or not.

+

Condition: Armstrong / Narcissistic number is the number in any given number base, which forms the total of the same number, when each of its digits is raised to the power of the number of digits in the number.

+
+

Sample 1:
+I/P: +153
+O/P: +Armstrong Number

+
+

Explanation: $ 1^3 + 5^3 + 3^3 = 153 $

+


+
+

Sample 2:
+I/P:
+407
+O/P:
+Armstrong Number
+Explanation: $ 4^3 + 0^3 + 7^3 = 407 $

+
+


+
+

Sample 3:
+I/P:
+107 +O/P:
+Not an Armstrong Number

+
+
+

Q8: Write a program to get a number n and print its multiplication table from 1 to 20.

+
+

Q9: Write a program to get the values of n and n numbers from the user and print average of the n numbers rounded off to 4 decimal places as output.
+Input:

+

First line contains the number n
+Next n lines contain n integers

+

Output:

+

Average of n numbers

+
+

Sample 1:
+I/P:
+10
+1
+5
+7
+22
+20
+40
+2
+53
+18
+-1
+O/p: 16.7

+
+
+

Q10: Write a program to get a number n and print the nth term of Fibonacci series as output.

+
+

Q11: Write a program to get two numbers as input and print their HCF as output.

+
+

Q12: Write a program to get two numbers as input and print their LCM as output.

+
+

Check Solution

+
+ + + + + \ No newline at end of file diff --git a/docs/Practice_code4.html b/docs/Practice_code4.html new file mode 100644 index 0000000..f780cad --- /dev/null +++ b/docs/Practice_code4.html @@ -0,0 +1,115 @@ + + + + + + + + Practice Functions + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Practice Functions

+

This Notebook Contains practice question for the note on Functions.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+
+

Q1: Write a program to define a function multiply which get two parameters and returns the product of them.

+
+

Q2: Write a program to create a function that gets sides of a rectangle and return its perimeter and area.

+
+

Q3: Write a program to create a function that gets a number n and a value s and prints the value n times as output.

+
+

Sample 1:
+I/P:
+10
+Hello
+
+O/P:
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello

+
+


+
+

Sample 2:
+I/P:
+5
+1
+
+O/P:
+1
+1
+1
+1
+1

+
+
+

Q4: Write a program to define a function to determine simple interest for given values of Principal, Rate p.a. and duration in years.
+Simple Interest, S.I. = $\dfrac{P \times R \times T}{100}$

+
+

Q5: Write a program to get a number n and and print the prime numbers from 1 to n. Use function to check if a number is prime or not.

+
+

Q6: Write a program to define a function to return factorial of the number passed in it (use recursion).

+
+

Q7: Write a program to define a function to return factorial of the number passed in it (without recursion).

+
+

Q8: Write a program to define a function that gets a year as input and print if it is a leap year or not.

+

Condition: A year is leap if it is either divisible 4 or 400 and not 100.

+
+

Q9: Write a program to define a function that returns the permutation of n and r.
+$\text{Permutation(n, r)} = {}^nP_r = \dfrac{n!}{(n-r)!}$

+
+

Q10: Write a program to define a function that returns the permutation of n and r. Use recursion to compute the factorials.
+$\text{Permutation(n, r)} = {}^nP_r = \dfrac{n!}{(n-r)!}$

+
+

Q11: Write a program to define a function that returns the permutation of n and r.
+$\text{Permutation(n, r)} = {}^nP_r$ = $\dfrac{n!}{(n-r)!} = n(n-1)(n-2)…r ~\text{terms}$

+
+

Q12: Write a program to define a function that returns the combination of n and r.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!}$

+
+

Q13: Write a program to define a function that returns the combinations of n and r. Use recursion to compute the factorials.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!}$

+
+

Q14: Write a program to define a function that returns the combinations of n and r.
+$\text{Combination(n, r)} = {}^nC_r = \dfrac{n!}{(n-r)!~r!} = \dfrac{n(n-1)(n-2)…r ~\text{terms}}{1 \times 2 \times 3… r ~\text{(r terms)}} = \displaystyle \prod_{i ~= ~0}^{r ~-~1} \dfrac{n-i}{i+1}$

+
+

Check Solution

+
+ + + + + \ No newline at end of file diff --git a/docs/Practice_code5.html b/docs/Practice_code5.html new file mode 100644 index 0000000..542b942 --- /dev/null +++ b/docs/Practice_code5.html @@ -0,0 +1,268 @@ + + + + + + + + List DS Practice + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

List DS Practice

+

This Notebook Contains practice question for the note on Lists.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+
+

Q1: Write a program to get a number n and n numbers as input and print them as a list.

+
+

Sample 1:
+I/p:
+3
+5
+2
+-20
+O/p: +[5, 2, -20]

+
+
+

Q2: Get the list of integers as input, sort them and print as output.

+
+

Sample 1:
+I/P:
+-1 110 -10 0 20 1 60
+O/P:
+[-10 -1 0 1 20 60 110]

+
+
+

Q3: Get a list of integers as input and print the even elements present in it. (No. of even elements > 1)

+
+

Sample 1:
+I/P: 10 20 5 -2 79 23335 40
+O/p: [10 20 -2 40]

+
+
+

Q4: Write a program to get a list of integers and print their product as output. (Use reduce method).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 13202000

+
+
+

Q5: Write a program to get a list of integers and print their sum as output. (Use sum method).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 90

+
+
+

Q6: Write a program to get a list of integers and print their sum as output. (use loops).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 90

+
+
+

Q7: Write a program to get a list of integers and print their product as output. (Use loops).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 13202000

+
+
+

Q8: Write a program to get a list of integers and print their average as output. (round off to 3 decimal places).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 12.857

+
+
+

Q9: Write a program to get a list of integers and print the maximum value as output. (Use max method).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 41

+
+
+

Q10: Write a program to get a list of integers and print the maximum value as output. (Use loops).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: 41

+
+
+

Q11: Write a program to get a list of integers and print the minimum value as output. (Use min method).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: -7

+
+
+

Q12: Write a program to get a list of integers and print the minimum value as output. (Use loops).

+
+

Sample 1:
+I/P: 10 20 5 41 -2 -7 23
+O/P: -7

+
+
+

Q13: Write a program to get a number n and print first n terms of Fibonacci series.

+
+

Q14: Write a program to get a list of string values as input and print the values at even position as output.

+
+

Sample 1:
+I/P: Hi First Second python STRING
+O/P: First python

+
+
+

Q15: Write a program to get a list of numbers as input and print their median as output.
+(Median is the center-most value of the sorted list)

+
+

Sample 1:
+I/P: 2 9 1 7 4 8
+O/P: 6.5

+
+


+
+

Sample 2:
+I/P: 1 7 8 6 3
+O/P: 3

+
+
+

Q16: Write a program to get a list of numbers as input and print their mode as output.
+(Mode is the most frequent value of the given list)

+
+

Sample 1:
+I/P: 2 9 1 1 4 1
+O/P: 1

+
+


+
+

Sample 2:
+I/P: 1 3 8 6 3
+O/P: 3

+
+
+

Q17: Write a program to get the number of rows n and n rows of a matrix and print each row as a list.

+
+

Sample 1: +I/P:
+3
+10 20 30
+1 2 3
+5 -4 -10
+O/P:
+[10, 20, 30]
+[1, 2, 3]
+[5, -4, -10]

+
+
+

Q18: Write a program to get the number of rows n and $n\times n$ matrix and print its transpose.

+
+

Sample1:
+I/P:
+3
+10 20 30
+1 2 3
+5 -4 -10
+O/P:
+10 1 5
+20 2 -4
+30 3 -10

+
+
+

Q19: Write a program to get number of rows r and columns c and two $r \times c$ matrices and print their sum as output.
+(No empty lines are provided in between the matrices)

+
+

Sample 1:
+4
+4
+9 13 5 2
+1 11 7 6
+3 7 4 1
+6 0 7 10
+-2 4 7 31
+6 9 12 6
+12 11 0 1
+9 10 2 3
+O/P:
+7 17 12 33
+7 20 19 12
+15 18 4 2
+15 10 9 13

+
+
+

Q20: Write a program to get number of rows r and no. of columns c and three $r \times c$ matrices and print their sum as output.
+(No empty lines are provided in between the matrices)

+
+

Sample 1:
+4
+4
+9 13 5 2
+1 11 7 6
+3 7 4 1
+6 0 7 10
+-2 4 7 31
+6 9 12 6
+12 11 0 1
+9 10 2 3
+0 2 8 6
+3 7 1 0
+0 0 1 2
+10 1 0 11
+O/P:
+7 19 20 39
+10 27 20 12
+15 18 5 4
+25 11 9 24

+
+
+

Q21: Write a program to get a $m \times n$ matrix and a $p \times q$ matrix (m, n, p, q given) and print their product as output.
+(No empty lines are provided in between the matrices)

+
+

Sample1:
+3
2
+-82 0
+-57 -95
+91 56
+2
4
+1 3 -11 24
+-59 42 -15 48
+O/P:
+-82 -246 902 -1968
+5548 -4161 2052 -5928
+-3213 2625 -1841 4872

+
+
+

Q22: Write a program to get a list of words and sort them in lexicographic order.

+
+

Check Solution

+
+ + + + + \ No newline at end of file diff --git a/docs/Practice_code6.html b/docs/Practice_code6.html new file mode 100644 index 0000000..dbe2144 --- /dev/null +++ b/docs/Practice_code6.html @@ -0,0 +1,57 @@ + + + + + + + + Strings Practice + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Strings Practice

+

This Notebook Contains practice question for the note on Strings.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+

Q1: Write a program to get a string and print its reverse as output.

+

Q2: Write a program to get a string and print elements in odd position as output.

+

Q3: Write a program to get a string and print elements in even position as output.

+

Q4: Write a program to get a alphabetic string and print vowels in them as output.

+

Q5: Write a program to get a string and print digits in them as output.

+

Q6: Write a program to get a string s and a substring x and print if the x is present in s as output.

+

Q7: Write a program to get a string and set the first letter of all the words in the string to upper case and print the modified string as output.

+

Q8: Write a program to get a name from the user and print if it is a valid name as output.
+Condition: Name is valid if contains only alphabets and there are at least 1 uppercase and 1 lowercase characters.

+

Q9: Write a program to get a variable name, replace all the white spaces with an underscore ” _ ” and print the modified string as output.

+

Q10: Write a program to get a string and print all the elements sorted in the alphabetical order as output.

+

Q11: Write a program to get a string and print the words in them in lexicographic order as output. The words in the string are delimited by a single whitespace (‘ ‘).

+
+ + + + + \ No newline at end of file diff --git a/docs/Practice_code7.html b/docs/Practice_code7.html new file mode 100644 index 0000000..10d3274 --- /dev/null +++ b/docs/Practice_code7.html @@ -0,0 +1,45 @@ + + + + + + + + Tuples Practice + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Tuples Practice

+

This Notebook Contains practice question for the note on Tuples.

+

Try working online at:
+Coding Ground - Tutorials Point
+Online Compiler and Debugger

+
+ + + + + \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..2b569ce --- /dev/null +++ b/docs/README.md @@ -0,0 +1,59 @@ +# Python Programming Notes + + + +This repository contains in depth notes for Python Programming. +For missing content, refer [Official Documentation](https://docs.python.org/) +For some short snippets in python, visit [30 seconds of code - python](https://www.30secondsofcode.org/python/p/1) +For short notes refer, [Cheat Sheet](Cheat_sheet.pdf) + +Books: + +1. A Byte of Python - Swaroopch + [Read Online](https://python.swaroopch.com) + [Download PDF or EPUB](https://github.com/swaroopch/byte-of-python/releases/latest) + [Purchase](https://swaroopch.com/buybook) + +2. Automate the Boring Stuff with Python by Al Sweigart + [Read Online](https://automatetheboringstuff.com/2e/) + [Purchase](https://www.amazon.in/Automate-Boring-Stuff-Python-2nd/dp/1593279922/ref=sr_1_3?crid=P8EQ7A13BCC7&dchild=1&keywords=automate+the+boring+stuff+with+python&qid=1622629604&sprefix=Automate+the+boring+%2Caps%2C317&sr=8-3) + +3. Beyond the Basic Stuff with Python by Al Sweigart + [Read Online](https://inventwithpython.com/beyond/) + [Purchase](https://www.amazon.in/Python-Beyond-Basics-Al-Sweigart/dp/1593279663/ref=sr_1_3?crid=3R7C1Q4GPS9WB&dchild=1&keywords=beyond+the+basic+stuff+with+python&qid=1622629740&sprefix=Beyond+the+basic+stuff+with+%2Caps%2C322&sr=8-3) + +### Sequence of notes: + +All the outputs are to be tested by using print statement. In the notes shared, if only names of variables/functions are given, please use print statement(s) in your code to get the output. + +
    +
  1. Installing and Using Python
  2. +
  3. Introduction to Python programming
  4. +
  5. Decision Control Statements in Python
  6. +
  7. Looping statements in Python
  8. +
  9. Functions in Python
  10. +
  11. Data Structures - Lists
  12. +
  13. Data Structures - String
  14. +
  15. Data Structures - Tuples
  16. +
  17. Data Structures - Dictionaries
  18. +
  19. Data Structures - Sets
  20. +
  21. Errors and Exception Handling
  22. +
  23. Modules and Packages
  24. +
  25. File Handling
  26. +
  27. Advanced I/O
  28. +
  29. Python Generators
  30. +
  31. Python Iterators
  32. +
  33. Numbers in Programming
  34. +
  35. Object Oriented Programming in Python - Part I
  36. +
  37. Object Oriented Programming in Python - Part II
  38. +
  39. Regular Expressions in Python
  40. +
+ +### Test questions: + +1. [Code Practice 1](Practice_code1.html); [Code Practice 1 Solution](Solution1.html) +2. [Code Practice 2](Practice_code2.html); [Code Practice 2 Solution](Solution2.html) +3. [Code Practice 3](Practice_code3.html); [Code Practice 3 Solution](Solution3.html) +4. [Code Practice 4](Practice_code4.html); [Code Practice 4 Solution](Solution4.html) +5. [Code Practice 5](Practice_code5.html); [Code Practice 5 Solution](Solution5.html) +6. [Code Practice 6](Practice_code6.html) diff --git a/docs/Solution1.html b/docs/Solution1.html new file mode 100644 index 0000000..1d0d9e2 --- /dev/null +++ b/docs/Solution1.html @@ -0,0 +1,436 @@ + + + + + + + + Solution For >Code Practice 1 + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Solution For <a href="Practice_code1.html">Code Practice 1</a>

+ +

IN [1]

+
# Question 1
+print('Hello World')
+
+

stdout

+
Hello World
+
+
+

IN [2]

+
# Question 2
+name = input('Enter your name\n')
+print(name)
+# Input: Prabhu
+
+

stdin

+
Enter your name
+ Prabhu
+
+
+

stdout

+
Prabhu
+
+
+

IN [3]

+
# Question 3
+name = input('Enter Your name\n')
+age = int(input('Enter your age\n'))
+print(name)
+print(age)
+# Input: Chandru
+# 19
+
+

stdin

+
Enter Your name
+ Chandru
+Enter your age
+ 19
+
+
+

stdout

+
Chandru
+19
+
+
+

IN [4]

+
# Question 4
+a = int(input())
+b=int(input())
+print(a+b)
+
+# Input:
+# 10
+# 12
+
+

stdin

+
 10
+ 12
+
+
+

stdout

+
22
+
+
+

IN [5]

+
# Question 5
+a = int(input())
+b = int(input())
+print(a+b)
+print(a-b)
+print(a*b)
+print(a/b)
+print(a//b)
+print(a%b)
+print(a**b)
+
+# Input: 14
+# 12
+
+

stdin

+
 14
+ 12
+
+
+

stdout

+
26
+2
+168
+1.1666666666666667
+1
+2
+56693912375296
+
+
+

IN [6]

+
# Question 6
+a = int(input())
+b = int(input())
+print('Sum of',a,'and',b,'is',a+b)
+print('Sum of %d and %d is %d'%(a,b,a+b))
+print('Sum of {} and {} is {}'.format(a,b,a+b))
+print(f'Sum of {a} and {b} is {a+b}')
+
+# Input: 10
+# 15
+
+

stdin

+
 10
+ 15
+
+
+

stdout

+
Sum of 10 and 15 is 25
+Sum of 10 and 15 is 25
+Sum of 10 and 15 is 25
+Sum of 10 and 15 is 25
+
+
+

IN [7]

+
# Question 7
+name = input()
+print(f'Good Morning, {name}')
+
+# Input: Jenyhin
+
+

stdin

+
 Jenyhin
+
+
+

stdout

+
Good Morning, Jenyhin
+
+
+

IN [1]

+
# Question 8
+side = int(input())
+print(4 * side)
+
+# Input: 4
+
+

stdin

+
 4
+
+
+

stdout

+
16
+
+
+

IN [2]

+
# Question 9
+side = int(input())
+print(side * side)
+
+# Input: 22
+
+

stdin

+
 22
+
+
+

stdout

+
484
+
+
+

IN [3]

+
# Question 10
+length = int(input())
+breadth = int(input())
+print(2 * (length + breadth))
+
+# Input: 22
+# 21
+
+

stdin

+
 22
+ 21
+
+
+

stdout

+
86
+
+
+

IN [4]

+
# Question 11
+length = int(input())
+breadth = int(input())
+print(length * breadth)
+
+# Input: 22
+# 21
+
+

stdin

+
 22
+ 21
+
+
+

stdout

+
462
+
+
+

IN [5]

+
# Question 12
+number_of_sides = int(input())
+side = int(input())
+print(side * number_of_sides)
+
+# Input: 7
+# 21
+
+

stdin

+
 7
+ 21
+
+
+

stdout

+
147
+
+
+

IN [6]

+
# Question 13
+base = int(input())
+height = int(input())
+print(0.5 * base * height)
+
+# Input: 22
+# 21
+
+

stdin

+
 22
+ 21
+
+
+

stdout

+
231.0
+
+
+

IN [7]

+
# Question 14
+radius = int(input())
+print(f'{2 * 3.14159 * radius: .3f}')
+
+# Input:  22
+
+

stdin

+
 22
+
+
+

stdout

+
 138.230
+
+
+

IN [9]

+
# Question 15
+radius = int(input())
+print(f'{3.14159 * radius * radius: .3f}')
+
+# Input: 21
+
+

stdin

+
 21
+
+
+

stdout

+
 1385.441
+
+
+

IN [11]

+
# Question 16
+a = int(input())
+b = int(input())
+c = int(input())
+s = (a + b + c)/2
+print(f'{ (s * (s-a) * (s-b) * (s-c))**0.5: .3f}')
+
+# Input: 3
+# 4
+# 5
+
+

stdin

+
 3
+ 4
+ 5
+
+
+

stdout

+
 6.000
+
+
+

IN [12]

+
# Question 17
+side = int(input())
+print(f'{ 3**0.5 * side * side / 4: .4f}')
+# Input: 31
+
+

stdin

+
 31
+
+
+

stdout

+
 416.1252
+
+
+

IN [13]

+
# Question 18
+base = int(input())
+height = int(input())
+print(f'{(base**2 + height**2)**0.5: .3f}')
+
+# Input: 12
+# 6
+
+

stdin

+
 12
+ 6
+
+
+

stdout

+
 13.416
+
+
+

IN [14]

+
# Question 19 
+side = int(input())
+print(side ** 3)
+
+# Input: 15
+
+

stdin

+
 15
+
+
+

stdout

+
3375
+
+
+

IN [15]

+
# Question 20
+side = int(input()) 
+print(6 * side ** 2)
+
+# Input: 15
+
+

stdin

+
 15
+
+
+

stdout

+
1350
+
+
+

IN [16]

+
# Question 21
+length = int(input()) 
+breadth = int(input()) 
+height = int(input()) 
+print(length*breadth*height)
+
+# Input: 43
+# 28
+# 35
+
+

stdin

+
 43
+ 28
+ 35
+
+
+

stdout

+
42140
+
+
+

IN [17]

+
# Question 22
+l = int(input()) 
+b = int(input()) 
+h = int(input()) 
+tsa = 2 * (l * b + b * h + h * l)
+print(tsa)
+
+# Input: 43
+# 28
+# 35
+
+

stdin

+
 43
+ 28
+ 35
+
+
+

stdout

+
7378
+
+
+

IN [None]

+

+
+
+ + + + + \ No newline at end of file diff --git a/docs/Solution2.html b/docs/Solution2.html new file mode 100644 index 0000000..62ecf20 --- /dev/null +++ b/docs/Solution2.html @@ -0,0 +1,313 @@ + + + + + + + + Solution For >Code Practice 2 + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Solution For <a href="Practice_code2.md">Code Practice 2</a>

+ +

IN [1]

+
# Question1
+n = int(input())
+print('Even' if n%2 == 0 else 'Odd')
+
+# Input: 15
+
+

stdin

+
 15
+
+
+

stdout

+
Odd
+
+
+

IN [2]

+
# Question 2
+n = int(input())
+if n > 0: print('Positive')
+elif n == 0: print('Zero')
+else: print('Negative')
+
+# Input: -7
+
+

stdin

+
 -7
+
+
+

stdout

+
Negative
+
+
+

IN [1]

+
# Question 3
+mark = int(input())
+if 90 < mark <= 100: print('O')
+elif 80 < mark <= 90: print('A+')
+elif 70 < mark <= 80: print('A')
+elif 60 < mark <= 70: print('B+')
+elif 50 <= mark <= 60: print('B')
+elif 0 <= mark < 50: print('Fail')
+else: print('Invalid')
+
+# Input: 85
+
+

stdin

+
 85
+
+
+

stdout

+
A+
+
+
+

IN [2]

+
# Question 4
+age = int(input())
+if age > 17: print('Eligible')
+else: print('Ineligible')
+
+# Input: 27
+
+

stdin

+
 27
+
+
+

stdout

+
Eligible
+
+
+

IN [None]

+
# Question 5
+
+

IN [1]

+
# Question 6 - Method 1
+ch = input()
+vowels=["a","e","i","o","u","A","E","I","O","U"] 
+if ch in vowels: 
+    print("vowel") 
+else: 
+    print("consonant")
+
+# Input: f
+
+

stdin

+
 f
+
+
+

stdout

+
consonant
+
+
+

IN [3]

+
# Question 6 - Method 2
+ch = input()
+if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u': 
+    print("vowel")
+elif ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U':
+    print('vowel')
+else: 
+    print("consonant")
+
+# Input: A
+
+

stdin

+
 A
+
+
+

stdout

+
vowel
+
+
+

IN [4]

+
# Question 6 - Method 3
+ch = input()
+vowels = 'aeiouAEIOU' 
+if ch in vowels: 
+    print("vowel") 
+else: 
+    print("consonant")
+
+# Input: G
+
+

stdin

+
 G
+
+
+

stdout

+
consonant
+
+
+

IN [5]

+
# Question 7 - Method 1
+n1 = int(input())
+n2 = int(input())
+if n1 > n2: print(n1)
+else: print(n2)
+
+# Input: 10
+# 15
+
+

stdin

+
 10
+ 15
+
+
+

stdout

+
15
+
+
+

IN [6]

+
# Question 7 - Method 2
+n1 = int(input())
+n2 = int(input())
+print(n1 if n1 > n2 else n2)
+
+# Input: 10
+# 7
+
+

stdin

+
 10
+ 7
+
+
+

stdout

+
10
+
+
+

IN [7]

+
# Question 8 - Method 1
+n1 = int(input()) 
+n2 = int(input()) 
+n3 = int(input())
+if n1 > n2 >= n3:
+    print(n1) 
+elif n2 > n1 >= n3:
+    print(n2) 
+else:
+    print(n3)
+
+# Input: 10
+# 5
+# -7
+
+

stdin

+
 10
+ 5
+ -7
+
+
+

stdout

+
10
+
+
+

IN [8]

+
# Question 8 - Method 2
+n1 = int(input()) 
+n2 = int(input()) 
+n3 = int(input())
+if n1 > n2 and n1 > n3: 
+    print(n1) 
+elif n2 > n1 and n2 > n3: 
+    print(n2) 
+else: 
+    print(n3)
+
+# Input: 10
+# 5
+# -7
+
+

stdin

+
 10
+ 5
+ -7
+
+
+

stdout

+
10
+
+
+

IN [9]

+
# Question 8 - Method 3
+n1 = int(input()) 
+n2 = int(input()) 
+n3 = int(input())
+if n1 > n2: 
+    if n1 > n3: 
+        print(n1)
+    else: 
+        print(n3)
+else: 
+    if n3 > n2:
+        print(n3)
+    else: 
+        print(n2)
+
+# Input: 5
+# -7
+# 10
+
+

stdin

+
 5
+ -7
+ 10
+
+
+

stdout

+
10
+
+
+

IN [12]

+
# Question 9
+n = int(input())  
+root = int(n ** (1/2))
+if root * root == n: 
+    print("perfect square") 
+else: 
+    print("not perfect square")
+
+# Input: 16
+
+

stdin

+
 16
+
+
+

stdout

+
perfect square
+
+
+

IN [None]

+

+
+
+ + + + + \ No newline at end of file diff --git a/docs/Solution3.html b/docs/Solution3.html new file mode 100644 index 0000000..8abfa92 --- /dev/null +++ b/docs/Solution3.html @@ -0,0 +1,104 @@ + + + + + + + + Solution for >Code Practice 3 + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Solution for <a href="Practice_code3.md">Code Practice 3</a>

+ +

IN [1]

+
# Question 1
+n = int(input())
+sum = 0
+for i in range(1,n+1):
+    sum += i
+print(sum)
+
+

stdin

+
 10
+
+
+

stdout

+
55
+
+
+

IN [3]

+
# Question 2
+n = int(input())
+sum = 0
+for i in range(n):
+    sum += int(input())
+print(sum)
+
+

stdin

+
 10
+ 1
+ 5
+ 7
+ 22
+ 20
+ 40
+ 2
+ 53
+ 18
+ -1
+
+
+

stdout

+
167
+
+
+

IN [5]

+
# Question 5
+n = int(input())
+fac = 1
+while n>0:
+    fac *= n
+    n -= 1
+print(fac)
+
+

stdin

+
 6
+
+
+

stdout

+
720
+
+
+

IN [None]

+

+
+
+ + + + + \ No newline at end of file diff --git a/docs/Solution4.html b/docs/Solution4.html new file mode 100644 index 0000000..eff758a --- /dev/null +++ b/docs/Solution4.html @@ -0,0 +1,120 @@ + + + + + + + + Solution for >Code Practice 4 + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Solution for <a href="Practice_code4.md">Code Practice 4</a>

+ +

IN [1]

+
# Question 1
+def multiply(x, y):
+    return x*y
+m = int(input())
+n = int(input())
+print(multiply(m, n))
+
+# Input: 
+# 10
+# 20
+
+

stdin

+
 10
+ 20
+
+
+

stdout

+
200
+
+
+

IN [2]

+
# Question 2
+def perimeter_area(l, b):
+    p = 2 * (l+b)
+    a = l * b
+    return p,a
+l = int(input())
+b = int(input())
+perimeter, area = perimeter_area(l, b)
+print(perimeter)
+print(area)
+# Input:
+# 15
+# 18
+
+

stdin

+
 15
+ 18
+
+
+

stdout

+
66
+270
+
+
+

IN [3]

+
# Question 3:
+def print_times(n, v):
+    for i in range(n):
+        print(v)
+    return
+
+n = int(input())
+s = input()
+print_times(n, s)
+
+

stdin

+
 10
+ Hello
+
+
+

stdout

+
Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+Hello
+
+
+

IN [None]

+

+
+
+ + + + + \ No newline at end of file diff --git a/docs/Solution5.html b/docs/Solution5.html new file mode 100644 index 0000000..cb39674 --- /dev/null +++ b/docs/Solution5.html @@ -0,0 +1,137 @@ + + + + + + + + Solution for >Code Practice 5 + + + + + + + + + + + + + +
+ Home +
+
+
+ +
+

Solution for <a href="Practice_code5.md">Code Practice 5</a>

+ +

IN [1]

+
# Question 1:
+n = int(input())
+list1 = list()
+for i in range(n):
+    list1.append(int(input()))
+print(list1)
+
+# Input: 3
+# 5
+# 2
+# -20
+
+

stdin

+
 3
+ 5
+ 2
+ -20
+
+
+

stdout

+
[5, 2, -20]
+
+
+

IN [2]

+
# Question 19
+r = int(input())
+c = int(input())
+
+matrix1 = [list(map(int,input().split())) for i in range(r)]
+matrix2 = [list(map(int,input().split())) for i in range(r)]
+
+for i in range(r): 
+    for j in range(c): 
+        print(matrix1[i][j] + matrix2[i][j], end=" ")  
+    print()
+
+

stdin

+
 4
+ 4
+ 9 13 5 2
+ 1 11 7 6
+ 3 7 4 1
+ 6 0 7 10 
+ -2 4 7 31
+ 6 9 12 6
+ 12 11 0 1
+ 9 10 2 3
+
+
+

stdout

+
7 17 12 33 
+7 20 19 12 
+15 18 4 2 
+15 10 9 13 
+
+
+

IN [1]

+
# Question 20
+r = int(input())
+c = int(input())
+
+matrix1 = [list(map(int,input().split())) for i in range(r)] 
+matrix2 = [list(map(int,input().split())) for i in range(r)]  
+matrix3 = [list(map(int,input().split())) for i in range(r)]
+
+for i in range(r): 
+    for j in range(c): 
+        print(matrix1[i][j] + matrix2[i][j] + matrix3[i][j], end=" ")  
+    print()
+
+

stdin

+
 4
+ 4
+ 9 13 5 2
+ 1 11 7 6
+ 3 7 4 1
+ 6 0 7 10
+ -2 4 7 31
+ 6 9 12 6
+ 12 11 0 1
+ 9 10 2 3
+ 0 2 8 6
+ 3 7 1 0
+ 0 0 1 2
+ 10 1 0 11
+
+
+

stdout

+
7 19 20 39 
+10 27 20 12 
+15 18 5 4 
+25 11 9 24 
+
+
+
+ + + + + \ No newline at end of file diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 0000000..c419263 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-cayman \ No newline at end of file diff --git a/docs/factorial_recursion.py b/docs/factorial_recursion.py new file mode 100644 index 0000000..fdcf734 --- /dev/null +++ b/docs/factorial_recursion.py @@ -0,0 +1,14 @@ +# Example using factorial (n! = 1 * 2 * 3 ... n) n! = n * (n-1)! +def factorial(n, indent=''): + print(indent, n) + if -1 < n <= 1: + print(indent, 1) + return 1 # End of recursion + else: + fac = n * factorial(n-1, indent+' ') # recursive calling + print(indent, fac) + return fac + +n = int(input()) +print(factorial(n)) +# Input: 6 \ No newline at end of file diff --git a/docs/prime_generator.py b/docs/prime_generator.py new file mode 100644 index 0000000..4094013 --- /dev/null +++ b/docs/prime_generator.py @@ -0,0 +1,27 @@ +from time import * +from itertools import * +from math import * + +def prime_gen(n): + num = 2 + while num <= n: + k = 2 + while k * k <= num: + if num % k == 0: + break + k += 1 + else: + yield num + num += 1 + +prime = 2 +prime_square = 4 +__primeval = 3 # private value + +if __name__ == '__main__': + t = time() + for i in prime_gen(10**2): + print(i) + # for i in islice(count(), 1, 10**3+1): + # print(i) + print(time()-t) diff --git a/docs/python-logo-4k.jpg b/docs/python-logo-4k.jpg new file mode 100644 index 0000000..b85c5d0 Binary files /dev/null and b/docs/python-logo-4k.jpg differ diff --git a/docs/python-logo.jpg b/docs/python-logo.jpg new file mode 100644 index 0000000..6930ce5 Binary files /dev/null and b/docs/python-logo.jpg differ diff --git a/docs/static/html_format.js b/docs/static/html_format.js new file mode 100644 index 0000000..e5cf4c8 --- /dev/null +++ b/docs/static/html_format.js @@ -0,0 +1,20 @@ +window.onload = (function () { + let tags = document.getElementsByTagName("pre"); + for (var i = 0; i < tags.length; ++i) { + tags[i].classList.add("prettyprint"); + } + tags = document.getElementsByTagName("code"); + // console.log(tags); + for (var i = 0; i < tags.length; ++i) { + if (tags[i].classList.contains("language-python")) { + tags[i].classList.add("lang-py"); + tags[i].classList.remove("language-python"); + } + if (tags[i].classList.contains("language-err")) { + tags[i].parentElement.classList.add("err"); + tags[i].parentElement.classList.remove("prettyprint"); + + } + } + PR.prettyPrint(); +}) \ No newline at end of file diff --git a/docs/static/main.css b/docs/static/main.css new file mode 100644 index 0000000..8731f48 --- /dev/null +++ b/docs/static/main.css @@ -0,0 +1,192 @@ +body { + font-family: "Times New Roman", Times, serif; +} + +div { + border: 2% solid #a0d0a0; + box-shadow: 2% 2% #a0d0a0; +} +ol, +ul { + margin-left: 5%; +} + +li { + margin-left: 5%; + padding-left: -5%; +} + +ol > p, +ul > p { + text-indent: 0%; +} +.outer { + list-style-type: decimal; + padding: 5%; +} + +.inner { + list-style-type: lower-alpha; + padding: 10%; +} +h1, +h6 { + color: #000080; + align-self: center; + align-items: center; + text-align: center; + padding: 1% 1% 1% 1%; +} +h2, +h4 { + color: #ff9933; +} +h3, +h5 { + margin-left: 2%; + color: #138808; +} +th, +thead { + border: 1px solid black; + padding: 1%; + /* width: max-content; */ + height: auto; + text-align: center; + border-collapse: collapse; + background-color: #ffcd94; +} + +td { + padding: 1%; + margin: 5%; + width: max-content; + max-width: 75%; + overflow: auto; + text-align: center; + border: 1px solid black; + border-collapse: collapse; +} + +table { + max-width: 100%; + /* width: max-content; */ + table-layout: auto; + border: 1px solid black; + border-collapse: collapse; + text-align: center; + align-self: center; + padding: 5%; + margin-left: auto; + margin-right: auto; +} +blockquote { + padding: 10px 20px; + font-size: 17.5px; +} + +blockquote > p { + text-indent: 0%; + margin-bottom: 0; + font-family: "Gill Sans", "Gill Sans MT", "Calibri", "Trebuchet MS", + sans-serif; + font-weight: 200; +} + +.card { + padding-left: 0; + padding-right: 0; +} + +img { + padding: 2%; + margin: 2%; + align-self: center; + width: max-content; + max-width: 75%; + border-radius: 1%; +} + +pre { + margin: 2%; + padding-left: 1.5%; + margin-left: 10%; + align-content: flex-start; + box-sizing: border-box; + background-color: #dddddd; +} + +pre > code > span.pln { + color: #01579b; +} + +code { + font-weight: bold; +} + +pre.err { + background-color: #e15344; + color: black; + padding-left: 2%; +} +mjx-container { + margin-left: 5%; + height: 5%; + font-size: 120%; +} +.foot { + text-align: center; +} + +@media (prefers-color-scheme: light) { + body { + background: #fff; + color: #333; + } + blockquote { + border-left: 7.5px solid #e83e8c; + background-color: #dddddd; + } + pre { + box-shadow: 4px 4px 7px 5px #777; + } +} +@media (prefers-color-scheme: dark) { + body { + background: #2e3331; /*#424b4b; #17202a; #1c2536;*/ + color: #ffffff; + } + img { + background: #a0d0a0; + } + table { + border-color: #dddddd; + } + td { + border-color: #dddddd; + } + th, + thead { + background-color: #aac7a6; + border-color: #dddddd; + color: #333; + } + h1, + a, + a:hover { + color: #c3eaff; + } + hr { + background-color: #a0d0a0; + } + code { + color: #baf7a6; + } + pre { + box-shadow: 4px 4px 7px 5px #222; + } + blockquote { + border-left: 7.5px solid #baf7a6; + background-color: #424b4b; + } +} diff --git a/docs/static/prettify.css b/docs/static/prettify.css new file mode 100644 index 0000000..006492c --- /dev/null +++ b/docs/static/prettify.css @@ -0,0 +1,101 @@ +.pln { + color: #000; +} +@media screen { + .str { + color: #080; + } + .kwd { + color: #008; + } + .com { + color: #800; + } + .typ { + color: #606; + } + .lit { + color: #066; + } + .pun, + .opn, + .clo { + color: #660; + } + .tag { + color: #008; + } + .atn { + color: #606; + } + .atv { + color: #080; + } + .dec, + .var { + color: #606; + } + .fun { + color: red; + } +} +@media print, projection { + .str { + color: #060; + } + .kwd { + color: #006; + font-weight: bold; + } + .com { + color: #600; + font-style: italic; + } + .typ { + color: #404; + font-weight: bold; + } + .lit { + color: #044; + } + .pun, + .opn, + .clo { + color: #440; + } + .tag { + color: #006; + font-weight: bold; + } + .atn { + color: #404; + } + .atv { + color: #060; + } +} +pre.prettyprint { + padding: 2px; + border: 1px solid #888; +} +ol.linenums { + margin-top: 0; + margin-bottom: 0; +} +li.L0, +li.L1, +li.L2, +li.L3, +li.L5, +li.L6, +li.L7, +li.L8 { + list-style-type: none; +} +li.L1, +li.L3, +li.L5, +li.L7, +li.L9 { + background: #eee; +} diff --git a/docs/static/prettify.js b/docs/static/prettify.js new file mode 100644 index 0000000..b101fd0 --- /dev/null +++ b/docs/static/prettify.js @@ -0,0 +1,792 @@ +!(function () { + var q = null; + window.PR_SHOULD_USE_CONTINUATION = !0; + (function () { + function S(a) { + function d(e) { + var b = e.charCodeAt(0); + if (b !== 92) return b; + var a = e.charAt(1); + return (b = r[a]) + ? b + : "0" <= a && a <= "7" + ? parseInt(e.substring(1), 8) + : a === "u" || a === "x" + ? parseInt(e.substring(2), 16) + : e.charCodeAt(1); + } + function g(e) { + if (e < 32) return (e < 16 ? "\\x0" : "\\x") + e.toString(16); + e = String.fromCharCode(e); + return e === "\\" || e === "-" || e === "]" || e === "^" ? "\\" + e : e; + } + function b(e) { + var b = e + .substring(1, e.length - 1) + .match( + /\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g + ), + e = [], + a = b[0] === "^", + c = ["["]; + a && c.push("^"); + for (var a = a ? 1 : 0, f = b.length; a < f; ++a) { + var h = b[a]; + if (/\\[bdsw]/i.test(h)) c.push(h); + else { + var h = d(h), + l; + a + 2 < f && "-" === b[a + 1] + ? ((l = d(b[a + 2])), (a += 2)) + : (l = h); + e.push([h, l]); + l < 65 || + h > 122 || + (l < 65 || + h > 90 || + e.push([Math.max(65, h) | 32, Math.min(l, 90) | 32]), + l < 97 || + h > 122 || + e.push([Math.max(97, h) & -33, Math.min(l, 122) & -33])); + } + } + e.sort(function (e, a) { + return e[0] - a[0] || a[1] - e[1]; + }); + b = []; + f = []; + for (a = 0; a < e.length; ++a) + (h = e[a]), + h[0] <= f[1] + 1 ? (f[1] = Math.max(f[1], h[1])) : b.push((f = h)); + for (a = 0; a < b.length; ++a) + (h = b[a]), + c.push(g(h[0])), + h[1] > h[0] && (h[1] + 1 > h[0] && c.push("-"), c.push(g(h[1]))); + c.push("]"); + return c.join(""); + } + function s(e) { + for ( + var a = e.source.match( + /\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g + ), + c = a.length, + d = [], + f = 0, + h = 0; + f < c; + ++f + ) { + var l = a[f]; + l === "(" + ? ++h + : "\\" === l.charAt(0) && + (l = +l.substring(1)) && + (l <= h ? (d[l] = -1) : (a[f] = g(l))); + } + for (f = 1; f < d.length; ++f) -1 === d[f] && (d[f] = ++x); + for (h = f = 0; f < c; ++f) + (l = a[f]), + l === "(" + ? (++h, d[h] || (a[f] = "(?:")) + : "\\" === l.charAt(0) && + (l = +l.substring(1)) && + l <= h && + (a[f] = "\\" + d[l]); + for (f = 0; f < c; ++f) "^" === a[f] && "^" !== a[f + 1] && (a[f] = ""); + if (e.ignoreCase && m) + for (f = 0; f < c; ++f) + (l = a[f]), + (e = l.charAt(0)), + l.length >= 2 && e === "[" + ? (a[f] = b(l)) + : e !== "\\" && + (a[f] = l.replace(/[A-Za-z]/g, function (a) { + a = a.charCodeAt(0); + return "[" + String.fromCharCode(a & -33, a | 32) + "]"; + })); + return a.join(""); + } + for (var x = 0, m = !1, j = !1, k = 0, c = a.length; k < c; ++k) { + var i = a[k]; + if (i.ignoreCase) j = !0; + else if ( + /[a-z]/i.test( + i.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi, "") + ) + ) { + m = !0; + j = !1; + break; + } + } + for ( + var r = { b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 }, + n = [], + k = 0, + c = a.length; + k < c; + ++k + ) { + i = a[k]; + if (i.global || i.multiline) throw Error("" + i); + n.push("(?:" + s(i) + ")"); + } + return RegExp(n.join("|"), j ? "gi" : "g"); + } + function T(a, d) { + function g(a) { + var c = a.nodeType; + if (c == 1) { + if (!b.test(a.className)) { + for (c = a.firstChild; c; c = c.nextSibling) g(c); + c = a.nodeName.toLowerCase(); + if ("br" === c || "li" === c) + (s[j] = "\n"), (m[j << 1] = x++), (m[(j++ << 1) | 1] = a); + } + } else if (c == 3 || c == 4) + (c = a.nodeValue), + c.length && + ((c = d + ? c.replace(/\r\n?/g, "\n") + : c.replace(/[\t\n\r ]+/g, " ")), + (s[j] = c), + (m[j << 1] = x), + (x += c.length), + (m[(j++ << 1) | 1] = a)); + } + var b = /(?:^|\s)nocode(?:\s|$)/, + s = [], + x = 0, + m = [], + j = 0; + g(a); + return { a: s.join("").replace(/\n$/, ""), d: m }; + } + function H(a, d, g, b) { + d && ((a = { a: d, e: a }), g(a), b.push.apply(b, a.g)); + } + function U(a) { + for (var d = void 0, g = a.firstChild; g; g = g.nextSibling) + var b = g.nodeType, + d = + b === 1 ? (d ? a : g) : b === 3 ? (V.test(g.nodeValue) ? a : d) : d; + return d === a ? void 0 : d; + } + function C(a, d) { + function g(a) { + for ( + var j = a.e, + k = [j, "pln"], + c = 0, + i = a.a.match(s) || [], + r = {}, + n = 0, + e = i.length; + n < e; + ++n + ) { + var z = i[n], + w = r[z], + t = void 0, + f; + if (typeof w === "string") f = !1; + else { + var h = b[z.charAt(0)]; + if (h) (t = z.match(h[1])), (w = h[0]); + else { + for (f = 0; f < x; ++f) + if (((h = d[f]), (t = z.match(h[1])))) { + w = h[0]; + break; + } + t || (w = "pln"); + } + if ( + (f = w.length >= 5 && "lang-" === w.substring(0, 5)) && + !(t && typeof t[1] === "string") + ) + (f = !1), (w = "src"); + f || (r[z] = w); + } + h = c; + c += z.length; + if (f) { + f = t[1]; + var l = z.indexOf(f), + B = l + f.length; + t[2] && ((B = z.length - t[2].length), (l = B - f.length)); + w = w.substring(5); + H(j + h, z.substring(0, l), g, k); + H(j + h + l, f, I(w, f), k); + H(j + h + B, z.substring(B), g, k); + } else k.push(j + h, w); + } + a.g = k; + } + var b = {}, + s; + (function () { + for ( + var g = a.concat(d), j = [], k = {}, c = 0, i = g.length; + c < i; + ++c + ) { + var r = g[c], + n = r[3]; + if (n) for (var e = n.length; --e >= 0; ) b[n.charAt(e)] = r; + r = r[1]; + n = "" + r; + k.hasOwnProperty(n) || (j.push(r), (k[n] = q)); + } + j.push(/[\S\s]/); + s = S(j); + })(); + var x = d.length; + return g; + } + function v(a) { + var d = [], + g = []; + a.tripleQuotedStrings + ? d.push([ + "str", + /^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/, + q, + "'\"", + ]) + : a.multiLineStrings + ? d.push([ + "str", + /^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, + q, + "'\"`", + ]) + : d.push([ + "str", + /^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/, + q, + "\"'", + ]); + a.verbatimStrings && g.push(["str", /^@"(?:[^"]|"")*(?:"|$)/, q]); + var b = a.hashComments; + b && + (a.cStyleComments + ? (b > 1 + ? d.push(["com", /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, q, "#"]) + : d.push([ + "com", + /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\n\r]*)/, + q, + "#", + ]), + g.push([ + "str", + /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/, + q, + ])) + : d.push(["com", /^#[^\n\r]*/, q, "#"])); + a.cStyleComments && + (g.push(["com", /^\/\/[^\n\r]*/, q]), + g.push(["com", /^\/\*[\S\s]*?(?:\*\/|$)/, q])); + if ((b = a.regexLiterals)) { + var s = (b = b > 1 ? "" : "\n\r") ? "." : "[\\S\\s]"; + g.push([ + "lang-regex", + RegExp( + "^(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*(" + + ("/(?=[^/*" + + b + + "])(?:[^/\\x5B\\x5C" + + b + + "]|\\x5C" + + s + + "|\\x5B(?:[^\\x5C\\x5D" + + b + + "]|\\x5C" + + s + + ")*(?:\\x5D|$))+/") + + ")" + ), + ]); + } + (b = a.types) && g.push(["typ", b]); + b = ("" + a.keywords).replace(/^ | $/g, ""); + b.length && + g.push(["kwd", RegExp("^(?:" + b.replace(/[\s,]+/g, "|") + ")\\b"), q]); + d.push(["pln", /^\s+/, q, " \r\n\t\u00a0"]); + b = "^.[^\\s\\w.$@'\"`/\\\\]*"; + a.regexLiterals && (b += "(?!s*/)"); + g.push( + ["lit", /^@[$_a-z][\w$@]*/i, q], + ["typ", /^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/, q], + ["pln", /^[$_a-z][\w$@]*/i, q], + [ + "lit", + /^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i, + q, + "0123456789", + ], + ["pln", /^\\[\S\s]?/, q], + ["pun", RegExp(b), q] + ); + return C(d, g); + } + function J(a, d, g) { + function b(a) { + var c = a.nodeType; + if (c == 1 && !x.test(a.className)) + if ("br" === a.nodeName) + s(a), a.parentNode && a.parentNode.removeChild(a); + else for (a = a.firstChild; a; a = a.nextSibling) b(a); + else if ((c == 3 || c == 4) && g) { + var d = a.nodeValue, + i = d.match(m); + if (i) + (c = d.substring(0, i.index)), + (a.nodeValue = c), + (d = d.substring(i.index + i[0].length)) && + a.parentNode.insertBefore(j.createTextNode(d), a.nextSibling), + s(a), + c || a.parentNode.removeChild(a); + } + } + function s(a) { + function b(a, c) { + var d = c ? a.cloneNode(!1) : a, + e = a.parentNode; + if (e) { + var e = b(e, 1), + g = a.nextSibling; + e.appendChild(d); + for (var i = g; i; i = g) (g = i.nextSibling), e.appendChild(i); + } + return d; + } + for (; !a.nextSibling; ) if (((a = a.parentNode), !a)) return; + for ( + var a = b(a.nextSibling, 0), d; + (d = a.parentNode) && d.nodeType === 1; + + ) + a = d; + c.push(a); + } + for ( + var x = /(?:^|\s)nocode(?:\s|$)/, + m = /\r\n?|\n/, + j = a.ownerDocument, + k = j.createElement("li"); + a.firstChild; + + ) + k.appendChild(a.firstChild); + for (var c = [k], i = 0; i < c.length; ++i) b(c[i]); + d === (d | 0) && c[0].setAttribute("value", d); + var r = j.createElement("ol"); + r.className = "linenums"; + for ( + var d = Math.max(0, (d - 1) | 0) || 0, i = 0, n = c.length; + i < n; + ++i + ) + (k = c[i]), + (k.className = "L" + ((i + d) % 10)), + k.firstChild || k.appendChild(j.createTextNode("\u00a0")), + r.appendChild(k); + a.appendChild(r); + } + function p(a, d) { + for (var g = d.length; --g >= 0; ) { + var b = d[g]; + F.hasOwnProperty(b) + ? D.console && console.warn("cannot override language handler %s", b) + : (F[b] = a); + } + } + function I(a, d) { + if (!a || !F.hasOwnProperty(a)) + a = /^\s*= l && (b += 2); + g >= B && (r += 2); + } + } finally { + if (f) f.style.display = h; + } + } catch (u) { + D.console && console.log((u && u.stack) || u); + } + } + var D = window, + y = ["break,continue,do,else,for,if,return,while"], + E = [ + [ + y, + "auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile", + ], + "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof", + ], + M = [ + E, + "alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where", + ], + N = [ + E, + "abstract,assert,boolean,byte,extends,final,finally,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient", + ], + O = [ + N, + "as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,internal,into,is,let,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var,virtual,where", + ], + E = [ + E, + "debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN", + ], + P = [ + y, + "and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None", + ], + Q = [ + y, + "alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END", + ], + W = [ + y, + "as,assert,const,copy,drop,enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,pub,pure,ref,self,static,struct,true,trait,type,unsafe,use", + ], + y = [y, "case,done,elif,esac,eval,fi,function,in,local,set,then,until"], + R = + /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/, + V = /\S/, + X = v({ + keywords: [ + M, + O, + E, + "caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END", + P, + Q, + y, + ], + hashComments: !0, + cStyleComments: !0, + multiLineStrings: !0, + regexLiterals: !0, + }), + F = {}; + p(X, ["default-code"]); + p( + C( + [], + [ + ["pln", /^[^]*(?:>|$)/], + ["com", /^<\!--[\S\s]*?(?:--\>|$)/], + ["lang-", /^<\?([\S\s]+?)(?:\?>|$)/], + ["lang-", /^<%([\S\s]+?)(?:%>|$)/], + ["pun", /^(?:<[%?]|[%?]>)/], + ["lang-", /^]*>([\S\s]+?)<\/xmp\b[^>]*>/i], + ["lang-js", /^]*>([\S\s]*?)(<\/script\b[^>]*>)/i], + ["lang-css", /^]*>([\S\s]*?)(<\/style\b[^>]*>)/i], + ["lang-in.tag", /^(<\/?[a-z][^<>]*>)/i], + ] + ), + ["default-markup", "htm", "html", "mxml", "xhtml", "xml", "xsl"] + ); + p( + C( + [ + ["pln", /^\s+/, q, " \t\r\n"], + ["atv", /^(?:"[^"]*"?|'[^']*'?)/, q, "\"'"], + ], + [ + ["tag", /^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i], + ["atn", /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i], + ["lang-uq.val", /^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/], + ["pun", /^[/<->]+/], + ["lang-js", /^on\w+\s*=\s*"([^"]+)"/i], + ["lang-js", /^on\w+\s*=\s*'([^']+)'/i], + ["lang-js", /^on\w+\s*=\s*([^\s"'>]+)/i], + ["lang-css", /^style\s*=\s*"([^"]+)"/i], + ["lang-css", /^style\s*=\s*'([^']+)'/i], + ["lang-css", /^style\s*=\s*([^\s"'>]+)/i], + ] + ), + ["in.tag"] + ); + p(C([], [["atv", /^[\S\s]+/]]), ["uq.val"]); + p(v({ keywords: M, hashComments: !0, cStyleComments: !0, types: R }), [ + "c", + "cc", + "cpp", + "cxx", + "cyc", + "m", + ]); + p(v({ keywords: "null,true,false" }), ["json"]); + p( + v({ + keywords: O, + hashComments: !0, + cStyleComments: !0, + verbatimStrings: !0, + types: R, + }), + ["cs"] + ); + p(v({ keywords: N, cStyleComments: !0 }), ["java"]); + p(v({ keywords: y, hashComments: !0, multiLineStrings: !0 }), [ + "bash", + "bsh", + "csh", + "sh", + ]); + p( + v({ + keywords: P, + hashComments: !0, + multiLineStrings: !0, + tripleQuotedStrings: !0, + }), + ["cv", "py", "python"] + ); + p( + v({ + keywords: + "caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END", + hashComments: !0, + multiLineStrings: !0, + regexLiterals: 2, + }), + ["perl", "pl", "pm"] + ); + p( + v({ + keywords: Q, + hashComments: !0, + multiLineStrings: !0, + regexLiterals: !0, + }), + ["rb", "ruby"] + ); + p(v({ keywords: E, cStyleComments: !0, regexLiterals: !0 }), [ + "javascript", + "js", + ]); + p( + v({ + keywords: + "all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,throw,true,try,unless,until,when,while,yes", + hashComments: 3, + cStyleComments: !0, + multilineStrings: !0, + tripleQuotedStrings: !0, + regexLiterals: !0, + }), + ["coffee"] + ); + p(v({ keywords: W, cStyleComments: !0, multilineStrings: !0 }), [ + "rc", + "rs", + "rust", + ]); + p(C([], [["str", /^[\S\s]+/]]), ["regex"]); + var Y = (D.PR = { + createSimpleLexer: C, + registerLangHandler: p, + sourceDecorator: v, + PR_ATTRIB_NAME: "atn", + PR_ATTRIB_VALUE: "atv", + PR_COMMENT: "com", + PR_DECLARATION: "dec", + PR_KEYWORD: "kwd", + PR_LITERAL: "lit", + PR_NOCODE: "nocode", + PR_PLAIN: "pln", + PR_PUNCTUATION: "pun", + PR_SOURCE: "src", + PR_STRING: "str", + PR_TAG: "tag", + PR_TYPE: "typ", + prettyPrintOne: (D.prettyPrintOne = function (a, d, g) { + var b = document.createElement("div"); + b.innerHTML = "
" + a + "
"; + b = b.firstChild; + g && J(b, g, !0); + K({ h: d, j: g, c: b, i: 1 }); + return b.innerHTML; + }), + prettyPrint: (D.prettyPrint = function (a, d) { + function g() { + for ( + var b = D.PR_SHOULD_USE_CONTINUATION ? c.now() + 250 : Infinity; + i < p.length && c.now() < b; + i++ + ) { + for (var d = p[i], j = h, k = d; (k = k.previousSibling); ) { + var m = k.nodeType, + o = (m === 7 || m === 8) && k.nodeValue; + if ( + o + ? !/^\??prettify\b/.test(o) + : m !== 3 || /\S/.test(k.nodeValue) + ) + break; + if (o) { + j = {}; + o.replace(/\b(\w+)=([\w%+\-.:]+)/g, function (a, b, c) { + j[b] = c; + }); + break; + } + } + k = d.className; + if ((j !== h || e.test(k)) && !v.test(k)) { + m = !1; + for (o = d.parentNode; o; o = o.parentNode) + if (f.test(o.tagName) && o.className && e.test(o.className)) { + m = !0; + break; + } + if (!m) { + d.className += " prettyprinted"; + m = j.lang; + if (!m) { + var m = k.match(n), + y; + if (!m && (y = U(d)) && t.test(y.tagName)) + m = y.className.match(n); + m && (m = m[1]); + } + if (w.test(d.tagName)) o = 1; + else + var o = d.currentStyle, + u = s.defaultView, + o = + (o = o + ? o.whiteSpace + : u && u.getComputedStyle + ? u + .getComputedStyle(d, q) + .getPropertyValue("white-space") + : 0) && "pre" === o.substring(0, 3); + u = j.linenums; + if (!(u = u === "true" || +u)) + u = (u = k.match(/\blinenums\b(?::(\d+))?/)) + ? u[1] && u[1].length + ? +u[1] + : !0 + : !1; + u && J(d, u, o); + r = { h: m, c: d, j: u, i: o }; + K(r); + } + } + } + i < p.length ? setTimeout(g, 250) : "function" === typeof a && a(); + } + for ( + var b = d || document.body, + s = b.ownerDocument || document, + b = [ + b.getElementsByTagName("pre"), + b.getElementsByTagName("code"), + b.getElementsByTagName("xmp"), + ], + p = [], + m = 0; + m < b.length; + ++m + ) + for (var j = 0, k = b[m].length; j < k; ++j) p.push(b[m][j]); + var b = q, + c = Date; + c.now || + (c = { + now: function () { + return +new Date(); + }, + }); + var i = 0, + r, + n = /\blang(?:uage)?-([\w.]+)(?!\S)/, + e = /\bprettyprint\b/, + v = /\bprettyprinted\b/, + w = /pre|xmp/i, + t = /^code$/i, + f = /^(?:pre|code|xmp)$/i, + h = {}; + g(); + }), + }); + typeof define === "function" && + define.amd && + define("google-code-prettify", [], function () { + return Y; + }); + })(); +})(); diff --git a/docs/vector.py b/docs/vector.py new file mode 100644 index 0000000..9386d20 --- /dev/null +++ b/docs/vector.py @@ -0,0 +1,97 @@ +# Class Vector. Stores the data of a 3d vector (Mathematical) +# Define suitable attributes and behaviour for the instances. +# Required: scalar// and vector// product, addition// +# Optional: angle between the vectors //, distance from a point, Magnitude//, ... +# ai + bj + ck + +from math import sqrt, acos + + +class Vector(object): + # Vector initialization + def __init__(self, /, x=0, y=0, z=0): + self.x = x # Distance along x-axis + self.y = y # Distance along y-axis + self.z = z # Distance along z-axis + self.magnitude = sqrt(x ** 2 + y ** 2 + z ** 2) # Magnitude of vector + + # Vector Addition + def add(self, obj): + x = self.x + obj.x + y = self.y + obj.y + z = self.z + obj.z + return Vector(x, y, z) + + def __add__(self, obj): + x = self.x + obj.x + y = self.y + obj.y + z = self.z + obj.z + return Vector(x, y, z) + + # Scalar Product + def dotProduct(self, obj): + return self.x*obj.x + self.y*obj.y + self.z*obj.z + + def __matmul__(self, obj): # Overriding builtin method for @ + return self.x*obj.x + self.y*obj.y + self.z*obj.z + + # Vector Product + def crossProduct(self, obj): + x = self.y * obj.z - self.z * obj.y + y = self.z * obj.x - self.x * obj.z + z = self.x * obj.y - self.y * obj.x + return Vector(x, y, z) + + def __mul__(self, obj): # Overriding builtin method for * + x = self.y * obj.z - self.z * obj.y + y = self.z * obj.x - self.x * obj.z + z = self.x * obj.y - self.y * obj.x + return Vector(x, y, z) + + # String representation of vector + def __repr__(self): + x = ( + f"i\u0302" if self.x == 1 else f"-i\u0302" if self.x == -1 else f"{self.x}i\u0302" + ) + y = ( + f" +j\u0302" + if self.y == 1 + else f" -j\u0302" + if self.y == -1 + else f" {self.y:+}j\u0302" + ) + z = ( + f" +k\u0302" + if self.z == 1 + else f" -k\u0302" + if self.z == -1 + else f" {self.z:+}k\u0302" + ) + return x + y + z + + # Angle between vectors + def vectorAngle(self, obj): + angle = self @ obj / (self.magnitude * obj.magnitude) + return acos(angle) + +print() +aVector = Vector(x=2, y=3, z=-1) # 2i + 3j - k +bVector = Vector(x=1, y=10, z=-3) # i + 10j - 3k + +print(aVector, aVector.magnitude) +print(bVector, bVector.magnitude) + +# Dot Product execution +print(f'\n{aVector.dotProduct(bVector)}') +print(aVector @ bVector) + +# Cross Product Execution +print(f'\n{aVector.crossProduct(bVector)}') +print(aVector * bVector) + +# Addition +print(f'\n{aVector.add(bVector)}') +print(aVector+bVector) + +# Angle between vectors +print(f'\n{aVector.vectorAngle(bVector)} rad') diff --git a/factorial_recursion.py b/factorial_recursion.py new file mode 100644 index 0000000..fdcf734 --- /dev/null +++ b/factorial_recursion.py @@ -0,0 +1,14 @@ +# Example using factorial (n! = 1 * 2 * 3 ... n) n! = n * (n-1)! +def factorial(n, indent=''): + print(indent, n) + if -1 < n <= 1: + print(indent, 1) + return 1 # End of recursion + else: + fac = n * factorial(n-1, indent+' ') # recursive calling + print(indent, fac) + return fac + +n = int(input()) +print(factorial(n)) +# Input: 6 \ No newline at end of file diff --git a/prime_generator.py b/prime_generator.py new file mode 100644 index 0000000..4094013 --- /dev/null +++ b/prime_generator.py @@ -0,0 +1,27 @@ +from time import * +from itertools import * +from math import * + +def prime_gen(n): + num = 2 + while num <= n: + k = 2 + while k * k <= num: + if num % k == 0: + break + k += 1 + else: + yield num + num += 1 + +prime = 2 +prime_square = 4 +__primeval = 3 # private value + +if __name__ == '__main__': + t = time() + for i in prime_gen(10**2): + print(i) + # for i in islice(count(), 1, 10**3+1): + # print(i) + print(time()-t) diff --git a/vector.py b/vector.py new file mode 100644 index 0000000..9386d20 --- /dev/null +++ b/vector.py @@ -0,0 +1,97 @@ +# Class Vector. Stores the data of a 3d vector (Mathematical) +# Define suitable attributes and behaviour for the instances. +# Required: scalar// and vector// product, addition// +# Optional: angle between the vectors //, distance from a point, Magnitude//, ... +# ai + bj + ck + +from math import sqrt, acos + + +class Vector(object): + # Vector initialization + def __init__(self, /, x=0, y=0, z=0): + self.x = x # Distance along x-axis + self.y = y # Distance along y-axis + self.z = z # Distance along z-axis + self.magnitude = sqrt(x ** 2 + y ** 2 + z ** 2) # Magnitude of vector + + # Vector Addition + def add(self, obj): + x = self.x + obj.x + y = self.y + obj.y + z = self.z + obj.z + return Vector(x, y, z) + + def __add__(self, obj): + x = self.x + obj.x + y = self.y + obj.y + z = self.z + obj.z + return Vector(x, y, z) + + # Scalar Product + def dotProduct(self, obj): + return self.x*obj.x + self.y*obj.y + self.z*obj.z + + def __matmul__(self, obj): # Overriding builtin method for @ + return self.x*obj.x + self.y*obj.y + self.z*obj.z + + # Vector Product + def crossProduct(self, obj): + x = self.y * obj.z - self.z * obj.y + y = self.z * obj.x - self.x * obj.z + z = self.x * obj.y - self.y * obj.x + return Vector(x, y, z) + + def __mul__(self, obj): # Overriding builtin method for * + x = self.y * obj.z - self.z * obj.y + y = self.z * obj.x - self.x * obj.z + z = self.x * obj.y - self.y * obj.x + return Vector(x, y, z) + + # String representation of vector + def __repr__(self): + x = ( + f"i\u0302" if self.x == 1 else f"-i\u0302" if self.x == -1 else f"{self.x}i\u0302" + ) + y = ( + f" +j\u0302" + if self.y == 1 + else f" -j\u0302" + if self.y == -1 + else f" {self.y:+}j\u0302" + ) + z = ( + f" +k\u0302" + if self.z == 1 + else f" -k\u0302" + if self.z == -1 + else f" {self.z:+}k\u0302" + ) + return x + y + z + + # Angle between vectors + def vectorAngle(self, obj): + angle = self @ obj / (self.magnitude * obj.magnitude) + return acos(angle) + +print() +aVector = Vector(x=2, y=3, z=-1) # 2i + 3j - k +bVector = Vector(x=1, y=10, z=-3) # i + 10j - 3k + +print(aVector, aVector.magnitude) +print(bVector, bVector.magnitude) + +# Dot Product execution +print(f'\n{aVector.dotProduct(bVector)}') +print(aVector @ bVector) + +# Cross Product Execution +print(f'\n{aVector.crossProduct(bVector)}') +print(aVector * bVector) + +# Addition +print(f'\n{aVector.add(bVector)}') +print(aVector+bVector) + +# Angle between vectors +print(f'\n{aVector.vectorAngle(bVector)} rad')