{"id":23452,"date":"2023-01-08T21:08:36","date_gmt":"2023-01-08T15:38:36","guid":{"rendered":"https:\/\/tocxten.com\/?page_id=23452"},"modified":"2024-02-04T20:29:42","modified_gmt":"2024-02-04T14:59:42","slug":"python-cheat-sheet","status":"publish","type":"page","link":"https:\/\/tocxten.com\/index.php\/python-cheat-sheet\/","title":{"rendered":"Python Cheat Sheet"},"content":{"rendered":"\n<p><strong>Dr.Thyagaraju G S and Palguni G T<\/strong>:<\/p>\n\n\n\n<p class=\"has-medium-font-size\">A Python cheat sheet is a quick reference guide that summarizes the most important features of the Python programming language. It typically includes information on syntax, data types, control structures, functions, and modules, among other things.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">Python cheat sheets are useful for both beginners and experienced developers who need a quick refresher on certain aspects of the language. They can also be used as study aids for learning Python, or as a handy reference guide when working on a project.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">Here are some of the items you might find on a Python cheat sheet:<\/p>\n\n\n\n<ul class=\"has-medium-font-size wp-block-list\"><li><strong>Basic syntax:<\/strong> how to define variables, assign values, and use operators<\/li><li><strong>Control structures<\/strong>: if\/else statements, loops (for and while), and conditional expressions<\/li><li><strong>Data types: <\/strong>integers, floats, booleans, strings, lists, tuples, sets, and dictionaries<\/li><li><strong>Functions:<\/strong> how to define and call functions, pass arguments, and use return values<\/li><li><strong>Modules:<\/strong> how to import and use built-in and third-party modules<\/li><li><strong>File I\/O: <\/strong>how to read from and write to files<\/li><li><strong>Exception handling:<\/strong> how to catch and handle errors and exceptions<\/li><li><strong>Regular expressions: <\/strong>how to use regular expressions to search and manipulate strings<\/li><li><strong>Object-oriented programming: <\/strong>how to define and use classes and objects<\/li><\/ul>\n\n\n\n<p class=\"has-medium-font-size\">Overall, a Python cheat sheet is a valuable resource for anyone who works with Python, and can help you save time and be more productive by providing quick and easy access to the most important features of the language.<\/p>\n\n\n\n<ol class=\"has-background wp-block-list\" style=\"background-color:#e8edf1;font-size:30px\"><li><strong>Zen of Python<\/strong><\/li><\/ol>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-7.png\" alt=\"\" class=\"wp-image-23463\" width=\"183\" height=\"57\"\/><\/figure>\n\n\n\n<p class=\"has-medium-font-size\">The Zen of Python is a collection of guiding principles for writing computer programs in the Python language. It was written by Tim Peters and is included as an easter egg in Python&#8217;s interpreter. Here are the 19 principles of the Zen of Python:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-8.png\" alt=\"\" class=\"wp-image-23464\" width=\"610\" height=\"411\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-8.png 837w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-8-300x202.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-8-768x518.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-8-760x512.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-8-600x404.png 600w\" sizes=\"auto, (max-width: 610px) 100vw, 610px\" \/><\/figure>\n\n\n\n<p class=\"has-medium-font-size\">These principles encourage Python programmers to write code that is clear, readable, and maintainable, even at the cost of being slightly more verbose or less &#8220;clever.&#8221; The Zen of Python emphasizes the importance of simplicity, readability, and elegance in code, as well as the importance of writing code that is easy to understand and modify over time. By following these principles, Python programmers can create programs that are not only functional but also easy to use, understand, and build upon.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e3e8ed;font-size:30px\"><strong>2.Python Keywords<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">Keywords in Python are the reserved words that have a special meaning and cannot be used as variable names or identifiers. Here&#8217;s a list of Python keywords:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-1024x260.png\" alt=\"\" class=\"wp-image-23453\" width=\"844\" height=\"214\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-1024x260.png 1024w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-300x76.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-768x195.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-1130x287.png 1130w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-760x193.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3-600x152.png 600w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-3.png 1237w\" sizes=\"auto, (max-width: 844px) 100vw, 844px\" \/><\/figure>\n\n\n\n<p class=\"has-medium-font-size\">These keywords are used to define the syntax and structure of the Python language. For example, <code>if<\/code>, <code>else<\/code>, and <code>elif<\/code> are used for conditional statements, <code>while<\/code> and <code>for<\/code> are used for loops, <code>def<\/code> is used to define functions, and <code>class<\/code> is used to define classes. It&#8217;s important to note that keywords cannot be used as variable names, so you should avoid using these words when naming your own variables in Python.<\/p>\n\n\n\n<p class=\"has-light-green-cyan-background-color has-background\"><strong>You can get a list of available keywords by using&nbsp;<code>help()<\/code>:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-4.png\" alt=\"\" class=\"wp-image-23454\" width=\"734\" height=\"314\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-4.png 953w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-4-300x129.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-4-768x330.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-4-760x326.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/01\/image-4-600x258.png 600w\" sizes=\"auto, (max-width: 734px) 100vw, 734px\" \/><\/figure>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e4e9ed;font-size:30px\">3.<strong>Comments <\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">In Python, comments are used to annotate code and provide additional information to the programmer or other readers of the code. Comments are ignored by the Python interpreter and are not executed as part of the program. There are two ways to write comments in Python:<\/p>\n\n\n\n<ol class=\"has-medium-font-size wp-block-list\"><li>Single-line comments: Single-line comments start with the hash (#) character and continue until the end of the line. For example:<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code># This is a single-line comment in Python\nprint(\"Hello, world!\")<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">2. Multi-line comments: Multi-line comments are also known as docstrings, and they can span multiple lines of code. They are enclosed in triple quotes (either single or double) at the beginning and end of the comment block. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\"\"\"\nThis is a multi-line comment or docstring\nIt can span multiple lines\n\"\"\"\nprint(\"Hello, world!\")<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">It is good practice to use comments to explain what your code does, especially for complex or unclear sections. Comments should be concise, clear, and helpful.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dbdfe3;font-size:26px\">4.<strong>Indentatio<\/strong>n<\/p>\n\n\n\n<p class=\"has-medium-font-size\">In Python, indentation is used to define the structure and scope of blocks of code. It is a way to visually group statements and indicate the level of nesting within a program. Python uses indentation to indicate the level of code blocks. Code blocks that are at the same level of indentation are considered to be part of the same block of code.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">The standard convention in Python is to use four spaces for indentation, although some developers may use a different number of spaces or even tabs. However, mixing tabs and spaces for indentation is not recommended, as it can lead to errors.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">Here&#8217;s an example of how indentation is used in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if x &gt; 0:\n    print(\"x is positive\")\nelse:\n    print(\"x is non-positive\")<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">In this code snippet, the <code>if<\/code> statement and the <code>else<\/code> statement are indented by four spaces, indicating that they are part of the same block of code. The <code>print<\/code> statements are also indented by four spaces within their respective blocks.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">It&#8217;s important to note that indentation is significant in Python, and incorrect indentation can cause syntax errors or change the meaning of a program. Therefore, it&#8217;s essential to maintain consistent and correct indentation throughout your code.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dee4e8;font-size:26px\">5.<strong>Statements<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">In Python, a statement is a unit of code that performs a specific action or operation. In Python, statements can be classified as simple or compound. Simple statements are those that comprise a single line of code and are terminated by a newline character. Compound statements, on the other hand, consist of one or more clauses and use indentation to define the block of code. Here are some examples of simple statements in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 5\nprint(\"Hello, world!\")<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">Both of these statements are simple, as they consist of a single line of code. Here&#8217;s an example of a compound statement in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if x &gt; 0:\n    print(\"x is positive\")\nelse:\n    print(\"x is non-positive\")<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">This compound statement consists of an <code>if<\/code> clause and an <code>else<\/code> clause, both of which are indented to indicate that they are part of the same block of code. Here&#8217;s another example of a compound statement that uses multiple clauses:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for i in range(10):\n    if i &lt; 5:\n        print(i, \"is less than 5\")\n    else:\n        print(i, \"is greater than or equal to 5\")<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">This compound statement consists of a <code>for<\/code> loop and an <code>if-else<\/code> statement, both of which are indented to indicate that they are part of the same block of code.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">In general, simple statements in Python are those that can be executed in a single step, while compound statements are those that require multiple steps to execute. Simple statements are often used for simple operations, such as assigning values to variables or printing messages to the console, while compound statements are used for more complex operations, such as looping, branching, or exception handling.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dce2e8;font-size:30px\"><strong>6.Variables <\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">In Python, variables are used to store data values that can be used later in the program. Variables are essentially names that refer to specific values in the computer&#8217;s memory. The value stored in a variable can be of different data types, such as numbers, strings, lists, tuples, and dictionaries.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Variables can store values of different types\nx = 5\ny = \"five\"\nz = True<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e4eaef;font-size:30px\"><strong>7.Data Types <\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">Python supports several built-in data types, which include: <\/p>\n\n\n\n<ol class=\"has-background has-medium-font-size wp-block-list\" style=\"background-color:#d9e7c3\"><li><strong>Numeric Types: <\/strong>Numeric types represent numeric values and can be divided into three categories:<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code># integer\nx = 5\n\n# float\ny = 3.14\n\n# complex\nz = 2 + 3j<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#c1e0c5\"><strong>2. Boolean Type<\/strong>: The boolean data type represents the truth values True and False.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># boolean\na = True\nb = False<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#b7d4ba\"><strong>3. Sequence Types:<\/strong><\/p>\n\n\n\n<ul class=\"has-medium-font-size wp-block-list\"><li><strong>Strings (str):<\/strong> Strings are sequences of characters enclosed in quotes, such as &#8220;hello&#8221; or &#8220;world&#8221;.<\/li><li><strong>Lists (list): <\/strong>Lists are mutable sequences of objects, which means that you can change their values after they have been created.<\/li><li><strong>Tuples (tuple): <\/strong>Tuples are similar to lists but are immutable, which means that you cannot change their values after they have been created.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code># string\ns = \"hello world\"\n\n# list\nl = &#91;1, 2, 3, \"four\", 5.0]\n\n# tuple\nt = (1, 2, 3, \"four\", 5.0)<\/code><\/pre>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#cbd9c7\"><strong>4. Set Types:<\/strong><\/p>\n\n\n\n<ul class=\"has-medium-font-size wp-block-list\"><li><strong>Sets (set): <\/strong>Sets are unordered collections of unique objects. Sets are mutable, which means that you can add or remove items from them.<\/li><li><strong>Frozen sets (frozenset):<\/strong> Frozen sets are similar to sets but are immutable, which means that you cannot change their values after they have been created.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code># set\ns = {1, 2, 3, 4}\n\n# frozenset\nfs = frozenset({1, 2, 3, 4})<\/code><\/pre>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#d3decc\"><strong>5. Mapping Types:<\/strong><\/p>\n\n\n\n<p>Dictionaries (dict): Dictionaries are unordered collections of key-value pairs. Dictionaries are mutable, which means that you can add or remove items from them.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Creating a dictionary\nmy_dict = {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n\n# Accessing values\nprint(my_dict&#91;\"name\"])  # Output: John\nprint(my_dict.get(\"age\"))  # Output: 30\n\n# Changing values\nmy_dict&#91;\"age\"] = 40\n\n# Adding a new key-value pair\nmy_dict&#91;\"country\"] = \"USA\"\n\n# Removing a key-value pair\ndel my_dict&#91;\"city\"]\n\n# Looping through keys\nfor key in my_dict:\n    print(key)\n\n# Looping through values\nfor value in my_dict.values():\n    print(value)\n\n\n# Looping through key-value pairs\nfor key, value in my_dict.items():\n    print(key, value)<\/code><\/pre>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#badbbb\">6.<strong> None <\/strong><\/p>\n\n\n\n<p>In Python, <strong><code>None<\/code> <\/strong>is a special built-in value that represents the absence of a value. It is often used as a placeholder or default value when you need to define a variable or function argument but don&#8217;t yet know the actual value. Here are some common uses of <code>None<\/code> in Python:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Default values:<\/strong> When defining a function that has an optional argument, you can use <code>None<\/code> as the default value, indicating that if the argument is not provided, it should be treated as if it were not passed at all. For example:<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>def my_function(arg1, arg2=None):\n    if arg2 is None:\n        arg2 = some_default_value\n    # rest of the function code<\/code><\/pre>\n\n\n\n<p>In this example, <code>arg2<\/code> is an optional argument that defaults to <code>None<\/code> if not provided. If <code>arg2<\/code> is <code>None<\/code>, the function assigns a default value to it.<\/p>\n\n\n\n<p>2. <strong>Placeholder values<\/strong>: When defining a variable or data structure that will be assigned a value later, you can use <code>None<\/code> as a placeholder value. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_var = None  # this variable will be assigned a value later\nmy_list = &#91;None] * 10  # this list has 10 elements, all initialized to None\n<\/code><\/pre>\n\n\n\n<p>3. <strong>Checking for absence of value<\/strong>: You can use <code>None<\/code> to check if a variable or function argument has been assigned a value. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if my_var is None:\n    print\n<\/code><\/pre>\n\n\n\n<p>4. Initialization : You can use <code>None<\/code> to initialize a variable when you don&#8217;t have a value for it yet.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_var = None<\/code><\/pre>\n\n\n\n<p>In this example, <code>my_var<\/code> is initialized to <code>None<\/code>, indicating that it has no value yet. Overall, <code>None<\/code> is a useful constant in Python that can be used to represent the absence of a value, and can help make your code more clear and concise<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dde1e5;font-size:30px\"><strong>8.Operators <\/strong><\/p>\n\n\n\n<p>In Python, operators are special symbols or keywords that are used to perform operations on values or variables. Here&#8217;s an overview of the different types of operators in Python:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Arithmetic Operators<\/strong>: Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, division, modulus, and exponentiation. Examples include <code>+<\/code>, <code>-<\/code>, <code>*<\/code>, <code>\/<\/code>, <code>%<\/code>, and <code>**<\/code>.<\/li><li><strong>Comparison Operators:<\/strong> Comparison operators are used to compare two values and return a Boolean value (True or False) depending on whether the comparison is true or false. Examples include <code>==<\/code>, <code>!=<\/code>, <code>&gt;<\/code>, <code>&lt;<\/code>, <code>&gt;=<\/code>, and <code>&lt;=<\/code>.<\/li><li><strong>Logical Operators: <\/strong>Logical operators are used to combine two or more Boolean expressions and return a Boolean value based on the result. Examples include <code>and<\/code>, <code>or<\/code>, and <code>not<\/code>.<\/li><li><strong>Assignment Operators: <\/strong>Assignment operators are used to assign values to variables. Examples include <code>=<\/code>, <code>+=<\/code>, <code>-=<\/code>, <code>*=<\/code>, <code>\/=<\/code>, and <code>%=<\/code>.<\/li><li><strong>Bitwise Operators:<\/strong> Bitwise operators are used to perform operations on the binary representation of values. Examples include <code>&amp;<\/code> (bitwise AND), <code>|<\/code> (bitwise OR), <code>^<\/code> (bitwise XOR), <code>&lt;&lt;<\/code> (left shift), and <code>&gt;&gt;<\/code> (right shift).<\/li><li><strong>Membership Operators:<\/strong> Membership operators are used to test whether a value or variable is a member of a sequence or collection. Examples include <code>in<\/code> and <code>not in<\/code>.<\/li><li>I<strong>dentity Operators:<\/strong> Identity operators are used to test whether two objects or variables refer to the same object in memory. Examples include <code>is<\/code> and <code>is not<\/code>.<\/li><\/ol>\n\n\n\n<p>These are the main categories of operators in Python, and there are many different operators within each category. Understanding these operators is essential for writing effective and efficient Python code.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e2e8ed;font-size:30px\"><strong>9.Python Control Statements <\/strong><\/p>\n\n\n\n<p>In Python, control statements are used to control the flow of execution of a program. They allow the program to make decisions based on conditions, execute code repeatedly, and skip or break out of loops. Here are the three main types of control statements in Python:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Conditional statements:<\/strong> Conditional statements are used to execute different blocks of code based on whether a condition is true or false. The most commonly used conditional statement in Python is the <code>if<\/code> statement. Other conditional statements include <code>elif<\/code> and <code>else<\/code>. Example:<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 5\nif x &lt; 10:\n    print(\"x is less than 10\")\nelif x &gt; 10:\n    print(\"x is greater than 10\")\nelse:\n    print(\"x is equal to 10\")<\/code><\/pre>\n\n\n\n<p>2. <strong>Loop statements: <\/strong>Loop statements are used to execute a block of code repeatedly. The two most commonly used loop statements in Python are the <code>for<\/code> loop and the <code>while<\/code> loop. Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for i in range(5):\n    print(i)\n\nwhile x &lt; 10:\n    print(x)\n    x += 1<\/code><\/pre>\n\n\n\n<p>              <\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\"><li><strong>Jump statements: J<\/strong>ump statements are used to change the normal flow of a program. The two most commonly used jump statements in Python are <code>break<\/code> and <code>continue<\/code>. Example:<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>for i in range(10):\n    if i == 5:\n        break\n    print(i)\n\nfor i in range(10):\n    if i == 5:\n        continue\n    print(i)<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dfe6eb;font-size:30px\"><strong>10.Pass <\/strong><\/p>\n\n\n\n<p>In Python, <code>pass<\/code> is a keyword that is used as a placeholder for an empty code block. It is used when you need to define a function, class, or loop that does nothing, but you need to have some code in that block to avoid a syntax error. The <code>pass<\/code> statement does not do anything; it simply serves as a placeholder to tell Python that the code block is intentional left blank. Here&#8217;s an example of using <code>pass<\/code> in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def my_function():\n    pass  # this function does nothing<\/code><\/pre>\n\n\n\n<p>In this example, we define a function called <code>my_function<\/code>, but since we have not yet implemented the code to do anything in the function, we use <code>pass<\/code> as a placeholder. This allows us to define the function without any syntax errors, and we can later fill in the function body with the actual code we want to execute.<\/p>\n\n\n\n<p>Another example could be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if x &gt; 5:\n    pass  # TODO: implement some code here\nelse:\n    print(\"x is less than or equal to 5\")<\/code><\/pre>\n\n\n\n<p>In this example, we use <code>pass<\/code> as a placeholder to remind ourselves that we need to implement some code in the <code>if<\/code> block when <code>x<\/code> is greater than 5. Overall, <code>pass<\/code> is a useful keyword in Python when you need to define a code block that does nothing, but you need to have something there for syntactic reasons.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dbe0e4;font-size:30px\"><strong>11.Functions <\/strong><\/p>\n\n\n\n<p>In Python, a function is a block of reusable code that performs a specific task. Functions are defined using the <code>def<\/code> keyword, followed by the function name and a set of parentheses containing any input parameters. The body of the function is indented and can contain any valid Python code. Here is an example of a simple function that takes two arguments and returns their sum:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def add_numbers(a, b):\n    sum = a + b\n    return sum<\/code><\/pre>\n\n\n\n<p>In the above example, the function name is <code>add_numbers<\/code> and it takes two input parameters <code>a<\/code> and <code>b<\/code>. The body of the function calculates the sum of the two input parameters and returns the result using the <code>return<\/code> keyword.<\/p>\n\n\n\n<p>To call the function and pass in arguments, you simply use the function name followed by the arguments in parentheses:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>result = add_numbers(5, 10)\nprint(result)  # Output: 15<\/code><\/pre>\n\n\n\n<p>Functions can also have optional parameters with default values, which can be useful in certain situations:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def greet(name, greeting=\"Hello\"):\n    print(greeting + \", \" + name + \"!\")<\/code><\/pre>\n\n\n\n<p>In the above example, the function <code>greet<\/code> takes two parameters, <code>name<\/code> and <code>greeting<\/code>, with <code>greeting<\/code> having a default value of &#8220;Hello&#8221;. If the <code>greeting<\/code> parameter is not provided, the function will use the default value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>greet(\"Alice\")  # Output: Hello, Alice!\ngreet(\"Bob\", \"Hi\")  # Output: Hi, Bob!<\/code><\/pre>\n\n\n\n<p>Functions can also return multiple values using tuples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def get_name_and_age():\n    name = input(\"Enter your name: \")\n    age = int(input(\"Enter your age: \"))\n    return (name, age)\n\nresult = get_name_and_age()\nprint(result&#91;0])  # Output: \"Alice\"\nprint(result&#91;1])  # Output: 25<\/code><\/pre>\n\n\n\n<p>In the above example, the <code>get_name_and_age<\/code> function returns a tuple containing the <code>name<\/code> and <code>age<\/code> variables. The <code>result<\/code> variable is then assigned to this tuple and the individual values can be accessed using their index.<\/p>\n\n\n\n<p><strong><em>Functions can be passed as arguments to other functions:<\/em><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def add_numbers(a, b):\n    return a + b\n\ndef multiply_numbers(a, b):\n    return a * b\n\ndef apply_operation(func, a, b):\n    return func(a, b)\n\nresult = apply_operation(add_numbers, 3, 5)\nprint(result)  # Output: 8\n\nresult = apply_operation(multiply_numbers, 3, 5)\nprint(result)  # Output: 15<\/code><\/pre>\n\n\n\n<p><strong><em>Functions can also be nested within other functions:<\/em><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def outer_function():\n    def inner_function():\n        print(\"Hello from inner function!\")\n    inner_function()\n\nouter_function()  # Output: Hello from inner function!<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e8edef;font-size:30px\"><strong>12.Built in Functions<\/strong><\/p>\n\n\n\n<p>Python has a large number of built-in functions that can be used without needing to define them first. Here are some commonly used built-in functions in Python:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><code>print()<\/code>: Used to display output to the console.<\/li><li><code>len()<\/code>: Used to get the length of a sequence (list, tuple, string, etc.).<\/li><li><code>type()<\/code>: Used to get the data type of a variable or object.<\/li><li><code>input()<\/code>: Used to get input from the user via the console.<\/li><li><code>str()<\/code>: Used to convert an object into a string.<\/li><li><code>int()<\/code>: Used to convert an object into an integer.<\/li><li><code>float()<\/code>: Used to convert an object into a floating-point number.<\/li><li><code>range()<\/code>: Used to create a sequence of numbers.<\/li><li><code>list()<\/code>: Used to create a list object from a sequence.<\/li><li><code>tuple()<\/code>: Used to create a tuple object from a sequence.<\/li><li><code>set()<\/code>: Used to create a set object from a sequence.<\/li><li><code>dict()<\/code>: Used to create a dictionary object from a sequence of key-value pairs.<\/li><li><code>max()<\/code>: Used to find the maximum value in a sequence.<\/li><li><code>min()<\/code>: Used to find the minimum value in a sequence.<\/li><li><code>sum()<\/code>: Used to find the sum of a sequence of numbers.<\/li><li><code>abs()<\/code>: Used to find the absolute value of a number.<\/li><li><code>round()<\/code>: Used to round off a number to a specified number of decimal places.<\/li><li><code>ord()<\/code>: Used to get the Unicode value of a character.<\/li><li><code>chr()<\/code>: Used to get the character corresponding to a Unicode value.<\/li><li><code>enumerate()<\/code>: Used to iterate over a sequence and get the index and value of each item.<\/li><\/ol>\n\n\n\n<ol class=\"wp-block-list\"><li><code><strong>print()<\/strong><\/code>: Used to display output to the console.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>print(\"Hello, world!\")\nOutput : Hello, world!<\/code><\/pre>\n\n\n\n<p>2. <code><strong>len()<\/strong><\/code>: Used to get the length of a sequence (list, tuple, string, etc.).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list = &#91;1, 2, 3, 4, 5]\nprint(len(my_list))\nOutput : 5<\/code><\/pre>\n\n\n\n<p>3.<code><strong>type()<\/strong><\/code>: Used to get the data type of a variable or object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_string = \"Hello, world!\"\nprint(type(my_string))\nOutput : &lt;class 'str'&gt;<\/code><\/pre>\n\n\n\n<p>4. <code><strong>input()<\/strong><\/code>: Used to get input from the user via the console.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>user_input = input(\"Enter your name: \")\nprint(\"Hello, \" + user_input + \"!\")\nOutput:\nEnter your name: Palguni\nHello, Palguni!<\/code><\/pre>\n\n\n\n<p>5. <strong><code>str()<\/code>:<\/strong> Used to convert an object into a string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_number = 123\nmy_string = str(my_number)\nprint(type(my_string))\nOutput :\n&lt;class 'str'&gt;<\/code><\/pre>\n\n\n\n<p>6. <code><strong>int()<\/strong><\/code>: Used to convert an object into an integer.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>7. <strong>range():<\/strong> The range() function returns a sequence of numbers from start to stop with a given step size.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for i in range(1, 10, 2):\n    print(i)\n<\/code><\/pre>\n\n\n\n<p>8. <strong>max() and min():<\/strong> The max() and min() functions return the maximum and minimum values from a sequence of numbers or characters.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;3, 5, 1, 2, 4]\nprint(max(numbers))\nprint(min(numbers))\n\nchars = &#91;'a', 'z', 'b', 'y']\nprint(max(chars))\nprint(min(chars))\n<\/code><\/pre>\n\n\n\n<p>9. <strong>abs(): <\/strong>The abs() function returns the absolute value of a number.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>num = -3.14\nprint(abs(num))<\/code><\/pre>\n\n\n\n<p>10. <strong>round():<\/strong> The round() function rounds a number to a specified number of decimal places.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>num = 3.14159\nprint(round(num, 2))\n<\/code><\/pre>\n\n\n\n<p>11. <strong>sorted(): <\/strong>The sorted() function sorts a sequence of numbers or characters in ascending order.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;3, 5, 1, 2, 4]\nsorted_numbers = sorted(numbers)\nprint(sorted_numbers)\n\nchars = &#91;'a', 'z', 'b', 'y']\nsorted_chars = sorted(chars)\nprint(sorted_chars)<\/code><\/pre>\n\n\n\n<p>12. <strong>sum(): <\/strong>The sum() function returns the sum of all the elements in a sequence of numbers.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;3, 5, 1, 2, 4]\nprint(sum(numbers))<\/code><\/pre>\n\n\n\n<p><strong>13<\/strong>.<strong>int(), float(),str(), bool():<\/strong>&nbsp;These functions are used to convert values to different data types.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = \"5\"\nprint(int(x))    # Output: 5\n\ny = 3.14\nprint(str(y))    # Output: \"3.14\"\n\nz = 0\nprint(bool(z))   # Output: False<\/code><\/pre>\n\n\n\n<p>These are just a few examples of the built-in functions available in Python. For a complete list, check the Python documentation.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#eef3f5;font-size:30px\"><strong>13.Lists <\/strong><\/p>\n\n\n\n<p>In Python, a list is a collection of elements that are ordered and mutable. Lists are one of the most commonly used data structures in Python, and they can contain elements of different data types, including integers, floats, strings, booleans, and other lists.<\/p>\n\n\n\n<p>Here are some characteristics of lists:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Lists are ordered, which means that the order of elements in a list is preserved.<\/li><li>Lists are mutable, which means that you can change the elements in a list after it has been created.<\/li><li>Lists can contain elements of different data types, including integers, floats, strings, booleans, and other lists.<\/li><li>Lists can be nested, which means that you can create lists of lists.<\/li><\/ul>\n\n\n\n<p>Lists are useful when you want to store a collection of related data that can be modified as needed. For example, you might use a list to store the names of students in a class or the temperatures in a particular city over a period of time.<\/p>\n\n\n\n<p>.Here&#8217;s the syntax for creating a list in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list = &#91;element1, element2, element3, ...]<\/code><\/pre>\n\n\n\n<p>Examples  for creating lists: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n# A list of integers\nnumbers = &#91;1, 2, 3, 4, 5]\n\n# A list of strings\nfruits = &#91;'apple', 'banana', 'cherry']\n\n# A list of mixed data types\nmixed_list = &#91;1, 'apple', 2.5, True]\n\n# A list of lists\nnested_list = &#91;&#91;1, 2, 3], &#91;4, 5, 6], &#91;7, 8, 9]]<\/code><\/pre>\n\n\n\n<p>You can create an empty list in Python by simply assigning a pair of square brackets <code>[]<\/code> to a variable, like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list = &#91;]<\/code><\/pre>\n\n\n\n<p>You can also create an empty list using the <code>list()<\/code> constructor, like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list = list()<\/code><\/pre>\n\n\n\n<p>You can also create an empty list and add elements to it later:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>empty_list = &#91;]\nempty_list.append(1)\nempty_list.append(2)\nempty_list.append(3)\nprint(empty_list)  # Output: &#91;1, 2, 3]<\/code><\/pre>\n\n\n\n<p>You can access elements of a list using their index (starting from 0):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4, 5]\nprint(numbers&#91;0])  # Output: 1\nprint(numbers&#91;2])  # Output: 3<\/code><\/pre>\n\n\n\n<p>You can also use negative indexing to access elements from the end of the list:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4, 5]\nprint(numbers&#91;-1])  # Output: 5\nprint(numbers&#91;-3])  # Output: 3<\/code><\/pre>\n\n\n\n<p>You can modify elements of a list by assigning a new value to their index:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4, 5]\nnumbers&#91;1] = 10\nprint(numbers)  # Output: &#91;1, 10, 3, 4, 5]<\/code><\/pre>\n\n\n\n<p>You can add elements to a list using the <code>append()<\/code> method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fruits = &#91;'apple', 'banana', 'cherry']\nfruits.append('orange')\nprint(fruits)  # Output: &#91;'apple', 'banana', 'cherry', 'orange']<\/code><\/pre>\n\n\n\n<p>You can insert elements at a specific index using the <code>insert()<\/code> method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4, 5]\nnumbers.insert(2, 10)\nprint(numbers)  # Output: &#91;1, 2, 10, 3, 4, 5]<\/code><\/pre>\n\n\n\n<p>You can remove elements from a list using the <code>remove()<\/code> method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fruits = &#91;'apple', 'banana', 'cherry', 'orange']\nfruits.remove('banana')\nprint(fruits)  # Output: &#91;'apple', 'cherry', 'orange']<\/code><\/pre>\n\n\n\n<p>You can also use the <code>pop()<\/code> method to remove an element at a specific index:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4, 5]\nnumbers.pop(2)\nprint(numbers)  # Output: &#91;1, 2, 4, 5]<\/code><\/pre>\n\n\n\n<p>You can check if an element is in a list using the <code>in<\/code> keyword:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fruits = &#91;'apple', 'banana', 'cherry']\nprint('apple' in fruits)  # Output: True\nprint('orange' in fruits)  # Output: False<\/code><\/pre>\n\n\n\n<p>You can sort a list using the <code>sort()<\/code> method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;3, 1, 4, 2, 5]\nnumbers.sort()\nprint(numbers)  # Output: &#91;1, 2, 3, 4, 5]<\/code><\/pre>\n\n\n\n<p>Reversing a list:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list.reverse()\nprint(my_list)      # Output: &#91;'two', 'five', 6, 3, 1]<\/code><\/pre>\n\n\n\n<p>Slicing a list:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(my_list&#91;1:4])  # Output: &#91;'five', 6, 3]\nprint(my_list&#91;:3])   # Output: &#91;'two', 'five', 6]\nprint(my_list&#91;2:])   # Output: &#91;6, 3, 1]<\/code><\/pre>\n\n\n\n<p>Length of a list:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(len(my_list))  # Output: 5<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dce2e5;font-size:30px\"><strong>14.Tuples <\/strong><\/p>\n\n\n\n<p>In Python, a tuple is a collection of elements that are ordered and immutable. Tuples are similar to lists, but they cannot be modified once they are created. Tuples are defined using parentheses instead of square brackets.<\/p>\n\n\n\n<p>Here are some characteristics of tuples:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Tuples are ordered, which means that the order of elements in a tuple is preserved.<\/li><li>Tuples are immutable, which means that once a tuple is created, you cannot change its elements.<\/li><li>Tuples can contain elements of different data types, including integers, floats, strings, booleans, and other tuples.<\/li><\/ul>\n\n\n\n<p>Tuples are useful when you want to group related data together, but you don&#8217;t want that data to be modified accidentally. For example, you might use a tuple to represent a point in two-dimensional space, where the first element of the tuple is the x-coordinate and the second element is the y-coordinate.<\/p>\n\n\n\n<p>Here&#8217;s the syntax for creating a tuple in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_tuple = (element1, element2, element3, ...)<\/code><\/pre>\n\n\n\n<p>Here are some examples of how to create tuples in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># A tuple of integers\nmy_tuple1 = (1, 2, 3, 4, 5)\n\n# A tuple of strings\nmy_tuple2 = ('apple', 'banana', 'cherry')\n\n# A tuple of mixed data types\nmy_tuple3 = (1, 'apple', 2.5, True)\n\n# A tuple with a single element\nmy_tuple4 = (1,)  # Note the comma after the element\n\n# A nested tuple\nnested_tuple = ((1, 2), (3, 4), (5, 6))<\/code><\/pre>\n\n\n\n<p>You can also create an empty tuple:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>empty_tuple = ()<\/code><\/pre>\n\n\n\n<p>You can access elements of a tuple using their index (starting from 0):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_tuple = ('apple', 'banana', 'cherry')\nprint(my_tuple&#91;0])  # Output: 'apple'\nprint(my_tuple&#91;2])  # Output: 'cherry'<\/code><\/pre>\n\n\n\n<p>You can also use negative indexing to access elements from the end of the tuple:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_tuple = ('apple', 'banana', 'cherry')\nprint(my_tuple&#91;-1])  # Output: 'cherry'\nprint(my_tuple&#91;-2])  # Output: 'banana'<\/code><\/pre>\n\n\n\n<p>Note that tuples are immutable, which means you cannot modify them once they are created. For example, the following code will raise a <code>TypeError<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_tuple = ('apple', 'banana', 'cherry')\nmy_tuple&#91;1] = 'orange'  # Raises TypeError: 'tuple' object does not support item assignment<\/code><\/pre>\n\n\n\n<p>You can, however, create a new tuple by concatenating existing tuples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_tuple1 = ('apple', 'banana', 'cherry')\nmy_tuple2 = ('orange', 'grape', 'mango')\nnew_tuple = my_tuple1 + my_tuple2\nprint(new_tuple)  # Output: ('apple', 'banana', 'cherry', 'orange', 'grape', 'mango')<\/code><\/pre>\n\n\n\n<p>You can also use the <code>tuple()<\/code> constructor to create a tuple from an iterable, such as a list:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list = &#91;1, 2, 3, 4, 5]\nmy_tuple = tuple(my_list)\nprint(my_tuple)  # Output: (1, 2, 3, 4, 5)<\/code><\/pre>\n\n\n\n<p>Finally, you can use tuple unpacking to assign values from a tuple to variables:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_tuple = ('apple', 'banana', 'cherry')\na, b, c = my_tuple\nprint(a)  # Output: 'apple'\nprint(b)  # Output: 'banana'\nprint(c)  # Output: 'cherry'<\/code><\/pre>\n\n\n\n<p>This can also be used to swap the values of two variables:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a = 1\nb = 2\na, b = b, a\nprint(a)  # Output: 2\nprint(b)  # Output: 1<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d9e1e5;font-size:26px\"><strong>15.Dictionaries <\/strong><\/p>\n\n\n\n<p>In Python, a dictionary is a collection of key-value pairs that are unordered and mutable. Dictionaries are sometimes called &#8220;associative arrays&#8221; or &#8220;hash tables&#8221; in other programming languages.<\/p>\n\n\n\n<p>Here are some characteristics of dictionaries:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Dictionaries are unordered, which means that the order of elements in a dictionary is not preserved.<\/li><li>Dictionaries are mutable, which means that you can change the values associated with a key after it has been created.<\/li><li>Keys in a dictionary must be unique and immutable, which means that they cannot be changed after they have been created. Common key types include strings and integers.<\/li><li>Values in a dictionary can be of any data type, including integers, floats, strings, booleans, lists, tuples, and other dictionaries.<\/li><\/ul>\n\n\n\n<p>Dictionaries are useful when you want to store data that can be accessed quickly by a key. For example, you might use a dictionary to store information about a person, where the keys are the person&#8217;s name, age, and address, and the values are the corresponding information.<\/p>\n\n\n\n<p>In Python, dictionaries are defined using curly braces {} and a colon : to separate keys and values. Here&#8217;s the general syntax for creating a dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_dict = {key1: value1, key2: value2, key3: value3, ...}<\/code><\/pre>\n\n\n\n<p>Here are some examples of dictionaries in Python:<\/p>\n\n\n\n<p>Example 1: A dictionary of names and ages<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>person_dict = {'Alice': 25, 'Bob': 30, 'Charlie': 35}<\/code><\/pre>\n\n\n\n<p>In this example, <code>person_dict<\/code> contains three key-value pairs, where the keys are strings representing the names and the values are integers representing the ages.<\/p>\n\n\n\n<p>Example 2: A dictionary of coordinates<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>point_dict = {'x': 10, 'y': 20}<\/code><\/pre>\n\n\n\n<p>In this example, <code>point_dict<\/code> contains two key-value pairs, where the keys are strings representing the coordinates and the values are integers representing the values of the coordinates.<\/p>\n\n\n\n<p>You can access the values in a dictionary using their keys. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(person_dict&#91;'Alice'])   # Output: 25\nprint(point_dict&#91;'y'])       # Output: 20<\/code><\/pre>\n\n\n\n<p>You can also add or modify key-value pairs in a dictionary by assigning a value to a new key, or by assigning a new value to an existing key:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>person_dict&#91;'David'] = 40   # add a new key-value pair\nperson_dict&#91;'Alice'] = 26   # modify the value associated with an existing key<\/code><\/pre>\n\n\n\n<p>Finally, you can use various dictionary methods to manipulate dictionaries. For example, you can use the <code>keys()<\/code> method to get a list of all the keys in a dictionary, and the <code>values()<\/code> method to get a list of all the values in a dictionary.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d6dfe3;font-size:30px\"><strong>16.Strings <\/strong><\/p>\n\n\n\n<p>In Python, a string is a sequence of characters enclosed in quotation marks (either single quotes or double quotes). Strings are a fundamental data type in Python, and they are used to represent textual data.<\/p>\n\n\n\n<p>Here are some characteristics of strings:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Strings are immutable, which means that once a string is created, you cannot change its contents. However, you can create a new string by concatenating or slicing existing strings.<\/li><li>Strings are iterable, which means that you can loop over the characters in a string using a <code>for<\/code> loop.<\/li><li>Strings can be indexed and sliced, which means that you can access individual characters or substrings within a string using square brackets [].<\/li><\/ul>\n\n\n\n<p>In Python, strings are created by enclosing a sequence of characters in either single quotes (&#8216;&#8230;&#8217;) or double quotes (&#8220;&#8230;&#8221;). Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_string = \"Hello, World!\"<\/code><\/pre>\n\n\n\n<p>In this example, <code>my_string<\/code> is a string that contains the characters &#8220;Hello, World!&#8221;.<\/p>\n\n\n\n<p>You can access individual characters in a string using square brackets [] and an index, where the index starts at 0 for the first character, 1 for the second character, and so on. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(my_string&#91;0])  # Output: 'H'<\/code><\/pre>\n\n\n\n<p>You can also use negative indices to access characters from the end of the string. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(my_string&#91;-1])  # Output: <\/code><\/pre>\n\n\n\n<p>You can concatenate strings using the <code>+<\/code> operator, or you can repeat a string using the <code>*<\/code> operator. Here are some examples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>greeting = \"Hello\"\nname = \"Alice\"\nmessage = greeting + \", \" + name + \"!\"\nprint(message)  # Output: \"Hello, Alice!\"\n\nrepeat_string = \"Python \" * 3\nprint(repeat_string)  # Output: \"Python Python Python \"<\/code><\/pre>\n\n\n\n<p>You can also use various string methods to manipulate strings, such as <code>upper()<\/code> to convert all the characters in a string to uppercase, <code>lower()<\/code> to convert all the characters to lowercase, <code>strip()<\/code> to remove whitespace from the beginning and end of a string, and many more. Here are some examples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_string = \"   Hello, World!   \"\nprint(my_string.strip())  # Output: \"Hello, World!\"\n\nmy_string = \"Hello, World!\"\nprint(my_string.upper())  # Output: \"HELLO, WORLD!\"<\/code><\/pre>\n\n\n\n<p>In summary, strings are a fundamental data type in Python that are used to represent textual data, and they can be manipulated in many different ways using various string methods.<\/p>\n\n\n\n<p>list of some common string handling methods in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># lower(): Converts all characters in a string to lowercase.\nmy_string = \"Hello, World!\"\nprint(my_string.lower())  # Output: \"hello, world!\n\n# upper(): Converts all characters in a string to uppercase.\nmy_string = \"Hello, World!\"\nprint(my_string.upper())  # Output: \"HELLO, WORLD!\"\n\n# strip(): Removes whitespace from the beginning and end of a string.\nmy_string = \"    Hello, World!   \"\nprint(my_string.strip())  # Output: \"Hello, World!\"\n\n# split(): Splits a string into a list of substrings based on a specified delimiter.\nmy_string = \"apple,banana,orange\"\nprint(my_string.split(\",\"))  # Output: &#91;'apple', 'banana', 'orange']\n\n#join(): Joins a list of strings into a single string using a specified delimiter.\nmy_list = &#91;'apple', 'banana', 'orange']\nprint(\",\".join(my_list))  # Output: \"apple,banana,orange\"\n\n# replace(): Replaces all occurrences of a specified substring in a string with another substring.\nmy_string = \"Hello, World!\"\nprint(my_string.replace(\"World\", \"Python\"))  # Output: \"Hello, Python!\"\n\n#startswith(): Returns True if a string starts with a specified substring.\nmy_string = \"Hello, World!\"\nprint(my_string.startswith(\"Hello\"))  # Output: True\n\n# endswith(): Returns True if a string ends with a specified substring.\nmy_string = \"Hello, World!\"\nprint(my_string.endswith(\"World!\"))  # Output: True\n\n#find(): Searches a string for a specified substring and returns the index of the first occurrence (or -1 if not found).\nmy_string = \"Hello, World!\"\nprint(my_string.find(\"World\"))  # Output: 7\n\n#count(): Counts the number of occurrences of a specified substring in a string.\nmy_string = \"Hello, World!\"\nprint(my_string.count(\"l\"))  # Output: 3<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d9dfe1;font-size:30px\"><strong>17.File Handling <\/strong><\/p>\n\n\n\n<p>Files are a way of storing and manipulating data on a computer&#8217;s file system. In Python, files are represented as objects, which provide methods for reading and writing data to and from the file.<\/p>\n\n\n\n<p>Python provides built-in functions for working with files, including <code>open()<\/code>, <code>close()<\/code>, <code>read()<\/code>, <code>write()<\/code>, and many others.<\/p>\n\n\n\n<p>The <code>open()<\/code> function is used to open a file and returns a file object. The function takes two arguments: the name of the file to open (including the path, if necessary), and the mode in which to open the file (e.g., read-only, write-only, or read-write). Here&#8217;s an example:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong><code>open()<\/code> function:<\/strong> This function is used to open a file and returns a file object. The function takes two arguments: the name of the file to open (including the path, if necessary), and the mode in which to open the file (e.g., read-only, write-only, or read-write).<\/li><\/ol>\n\n\n\n<p>Syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>file = open(file_name, mode)\nExample:\nfile = open(\"myfile.txt\", \"r\")<\/code><\/pre>\n\n\n\n<p>2.<strong><code>close()<\/code> method:<\/strong> This method is used to close an opened file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Syntax\nfile.close()\n# Example \nfile = open(\"myfile.txt\", \"r\")\n# do something with the file\nfile.close()<\/code><\/pre>\n\n\n\n<p>3. <strong><code>read()<\/code> method<\/strong>: This method is used to read data from a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Syntax:\ndata = file.read(size)\n# Example : \nfile = open(\"myfile.txt\", \"r\")\ndata = file.read()\nprint(data)\nfile.close()<\/code><\/pre>\n\n\n\n<p>4. <strong><code>write()<\/code> method:<\/strong> This method is used to write data to a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#Syntax:\nfile.write(data)\n#Example :\nfile = open(\"myfile.txt\", \"w\")\nfile.write(\"Hello, World!\")\nfile.close()<\/code><\/pre>\n\n\n\n<p>5. <strong><code>readline()<\/code> method:<\/strong> This method is used to read a single line from a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong># Syntax<\/strong>\nline = file.readline()\n<strong>#Example:<\/strong>\nfile = open(\"myfile.txt\", \"r\")\nline = file.readline()\nprint(line)\nfile.close()<\/code><\/pre>\n\n\n\n<p>6<strong>. <code>writelines()<\/code> method: <\/strong>This method is used to write a list of lines to a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong># Syntax<\/strong>\nfile.writelines(lines)\n<strong># Example<\/strong>\nfile = open(\"myfile.txt\", \"w\")\nlines = &#91;\"line 1\\n\", \"line 2\\n\", \"line 3\\n\"]\nfile.writelines(lines)\nfile.close()<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dce3e6;font-size:26px\"><strong>18.Object Oriented Programming in Python<\/strong><\/p>\n\n\n\n<p>Object-oriented programming (OOP) is a programming paradigm that emphasizes the use of objects, which are instances of classes that encapsulate data and behavior. In Python, you can define classes and create objects from them to implement OOP. <\/p>\n\n\n\n<p>Here&#8217;s an example of a simple class definition:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n        \n    def say_hello(self):\n        print(f\"Hello, my name is {self.name} and I am {self.age} years old.\")<\/code><\/pre>\n\n\n\n<p>In this example, we define a <code>Person<\/code> class that has two attributes (<code>name<\/code> and <code>age<\/code>) and one method (<code>say_hello<\/code>). The <code>__init__<\/code> method is a special method that is called when an object of the class is created. It initializes the attributes of the object with the values passed in as arguments. To create an object of the <code>Person<\/code> class, we can use the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p = Person(\"Alice\", 30)<\/code><\/pre>\n\n\n\n<p>In this example, we create a <code>Person<\/code> object named <code>p<\/code> with the name &#8220;Alice&#8221; and age 30. We can then call the <code>say_hello<\/code> method on the <code>p<\/code> object like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p.say_hello()<\/code><\/pre>\n\n\n\n<p>In this example, we create a <code>Person<\/code> object named <code>p<\/code> with the name &#8220;Alice&#8221; and age 30. We can then call the <code>say_hello<\/code> method on the <code>p<\/code> object like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p.say_hello()<\/code><\/pre>\n\n\n\n<p>This will print &#8220;Hello, my name is Alice and I am 30 years old.&#8221; to the console. <\/p>\n\n\n\n<p>Here&#8217;s another example that shows how to define a subclass of an existing class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Student(Person):\n    def __init__(self, name, age, major):\n        super().__init__(name, age)\n        self.major = major\n        \n    def say_hello(self):\n        print(f\"Hello, my name is {self.name} and I am a {self.major} major.\")<\/code><\/pre>\n\n\n\n<p>In this example, we define a <code>Student<\/code> class that is a subclass of the <code>Person<\/code> class. The <code>Student<\/code> class adds a new attribute (<code>major<\/code>) and overrides the <code>say_hello<\/code> method to print a different message.<\/p>\n\n\n\n<p>To create a <code>Student<\/code> object, we can use the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>s = Student(\"Bob\", 20, \"Computer Science\")<\/code><\/pre>\n\n\n\n<p>In this example, we create a <code>Student<\/code> object named <code>s<\/code> with the name &#8220;Bob&#8221;, age 20, and major &#8220;Computer Science&#8221;.<\/p>\n\n\n\n<p>We can then call the <code>say_hello<\/code> method on the <code>s<\/code> object like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>s.say_hello()<\/code><\/pre>\n\n\n\n<p>This will print &#8220;Hello, my name is Bob and I am a Computer Science major.&#8221; to the console.<\/p>\n\n\n\n<p>These are just a few examples of how to use object-oriented programming in Python. By defining classes and creating objects, you can encapsulate data and behavior in a way that makes your code more modular, reusable, and easier to maintain.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dbe2e5;font-size:26px\"><strong>19.Decorators<\/strong><\/p>\n\n\n\n<p>Decorators in Python are functions that can modify the behavior of other functions or classes. They allow you to add functionality to existing code without modifying it directly. Decorators are typically used for implementing cross-cutting concerns such as logging, authentication, and caching.<\/p>\n\n\n\n<p>Here&#8217;s an example of a simple decorator function that adds logging to a function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def log(func):\n    def wrapper(*args, **kwargs):\n        print(f\"Calling function {func.__name__}\")\n        return func(*args, **kwargs)\n    return wrapper<\/code><\/pre>\n\n\n\n<p>In this example, the <code>log<\/code> function takes another function <code>func<\/code> as an argument and returns a new function <code>wrapper<\/code>. The <code>wrapper<\/code> function logs the name of the function being called and then calls the original function <code>func<\/code> with the same arguments.<\/p>\n\n\n\n<p>To use the <code>log<\/code> decorator, you simply apply it to a function by placing the <code>@log<\/code> decorator above the function definition:<\/p>\n\n\n\n<p>In this example, the <code>add<\/code> function is decorated with the <code>log<\/code> decorator. When the <code>add<\/code> function is called, the <code>log<\/code> decorator will be applied and the name of the function will be logged to the console.<\/p>\n\n\n\n<p>Here&#8217;s another example of a decorator that adds caching to a function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def cache(func):\n    cache = {}\n    def wrapper(*args):\n        if args in cache:\n            return cache&#91;args]\n        else:\n            result = func(*args)\n            cache&#91;args] = result\n            return result\n    return wrapper<\/code><\/pre>\n\n\n\n<p>In this example, the <code>cache<\/code> decorator maintains a cache of results for the decorated function. When the decorated function is called with the same arguments as before, the cached result is returned instead of recomputing the result.<\/p>\n\n\n\n<p>To use the <code>cache<\/code> decorator, you simply apply it to a function by placing the <code>@cache<\/code> decorator above the function definition:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@cache\ndef fibonacci(n):\n    if n &lt; 2:\n        return n\n    else:\n        return fibonacci(n-1) + fibonacci(n-2)<\/code><\/pre>\n\n\n\n<p>In this example, the <code>fibonacci<\/code> function is decorated with the <code>cache<\/code> decorator. When the <code>fibonacci<\/code> function is called with the same argument as before, the cached result will be returned instead of recomputing the result.<\/p>\n\n\n\n<p>These are just a few examples of how to use decorators in Python. Decorators are a powerful tool that can be used to modify the behavior of functions or classes in a flexible and modular way.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dae4e8;font-size:26px\"><strong>20.Exception Handling<\/strong><\/p>\n\n\n\n<p>Exception handling in Python is a way to handle errors and exceptions that may occur during program execution. It allows you to gracefully handle errors and prevent your program from crashing.<\/p>\n\n\n\n<p>In Python, you can use the <code>try-except<\/code> block to handle exceptions. The <code>try<\/code> block contains the code that may raise an exception, while the <code>except<\/code> block contains the code to handle the exception. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    num1 = int(input(\"Enter a number: \"))\n    num2 = int(input(\"Enter another number: \"))\n    result = num1 \/ num2\n    print(f\"The result is {result}\")\nexcept ZeroDivisionError:\n    print(\"Error: You cannot divide by zero.\")\nexcept ValueError:\n    print(\"Error: You must enter a valid number.\")<\/code><\/pre>\n\n\n\n<p>In this example, the <code>try<\/code> block prompts the user to enter two numbers and performs division. If an error occurs, the corresponding <code>except<\/code> block is executed. If a <code>ZeroDivisionError<\/code> occurs, a message is printed indicating that the user cannot divide by zero. If a <code>ValueError<\/code> occurs, a message is printed indicating that the user must enter a valid number.<\/p>\n\n\n\n<p>You can also use the <code>finally<\/code> block to execute code after the <code>try<\/code> and <code>except<\/code> blocks, regardless of whether an exception occurred. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    f = open(\"file.txt\", \"r\")\n    data = f.read()\n    print(data)\nexcept FileNotFoundError:\n    print(\"Error: The file does not exist.\")\nfinally:\n    f.close()<\/code><\/pre>\n\n\n\n<p>In this example, the <code>try<\/code> block attempts to open a file and read its contents. If the file does not exist, a <code>FileNotFoundError<\/code> is raised and a message is printed. The <code>finally<\/code> block ensures that the file is closed, regardless of whether an exception occurred.<\/p>\n\n\n\n<p>You can also define your own custom exceptions by subclassing the <code>Exception<\/code> class. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class MyException(Exception):\n    pass\n\ntry:\n    x = 10\n    if x &gt; 5:\n        raise MyException(\"x is too big\")\nexcept MyException as e:\n    print(e)<\/code><\/pre>\n\n\n\n<p>In this example, a custom exception <code>MyException<\/code> is defined by subclassing the <code>Exception<\/code> class. The <code>raise<\/code> statement is used to raise the <code>MyException<\/code> exception with a custom message. The <code>except<\/code> block catches the <code>MyException<\/code> exception and prints the custom message.<\/p>\n\n\n\n<p>Exception handling is an important part of writing robust and reliable code. By handling exceptions gracefully, you can prevent your program from crashing and provide a better user experience.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#c1ccd1;font-size:26px\"><strong>21.Modules in Python<\/strong><\/p>\n\n\n\n<p>In Python, a module is a file that contains Python definitions and statements. It is used to group related code together, so it can be easily imported and reused in other Python programs. Modules can be written in Python itself or in a language like C and loaded dynamically into Python.<\/p>\n\n\n\n<p>A module can contain functions, classes, and variables, which can be accessed using the dot notation after importing the module. For example, if we have a module called <code>my_module.py<\/code>, which contains a function called <code>my_function()<\/code>, we can import and use it in another Python program like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import my_module\n\nresult = my_module.my_function()<\/code><\/pre>\n\n\n\n<p>Python has a large number of built-in modules that provide useful functionality, such as <code>os<\/code> for interacting with the operating system, <code>datetime<\/code> for working with dates and times, and <code>random<\/code> for generating random numbers. Additionally, Python users can create their own modules and share them with others, either by publishing them on the web or by packaging them in libraries.<\/p>\n\n\n\n<p>Here are some examples of Python modules:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><code>random<\/code> module &#8211; provides functions for generating random numbers, choosing random elements from a list, and shuffling sequences randomly.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\n\n# Generate a random integer between 1 and 100\nrandom_number = random.randint(1, 100)\nprint(random_number)\n\n# Choose a random element from a list\nfruits = &#91;\"apple\", \"banana\", \"cherry\"]\nrandom_fruit = random.choice(fruits)\nprint(random_fruit)\n\n# Shuffle a list randomly\nrandom.shuffle(fruits)\nprint(fruits)<\/code><\/pre>\n\n\n\n<p>2. <strong><code>math<\/code> module<\/strong> &#8211; provides mathematical functions like trigonometric functions, logarithmic functions, and mathematical constants.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import math\n\n# Find the sine of pi\/2\nsin_value = math.sin(math.pi\/2)\nprint(sin_value)\n\n# Find the logarithm of 1000 to base 10\nlog_value = math.log10(1000)\nprint(log_value)\n\n# Find the value of pi\npi_value = math.pi\nprint(pi_value)<\/code><\/pre>\n\n\n\n<p>3. <strong><code>os<\/code> module <\/strong>&#8211; provides functions for interacting with the operating system, such as working with files and directories.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\n# Create a new directory\nos.mkdir(\"new_directory\")\n\n# Check if a file exists\nfile_exists = os.path.exists(\"file.txt\")\nprint(file_exists)\n\n# Get the current working directory\ncurrent_directory = os.getcwd()\nprint(current_directory)<\/code><\/pre>\n\n\n\n<p>4. <strong><code>datetime<\/code> module<\/strong> &#8211; provides functions for working with dates and times. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import datetime\n\n# Get the current date and time\ncurrent_datetime = datetime.datetime.now()\nprint(current_datetime)\n\n# Create a date object for a specific date\ndate = datetime.date(2023, 3, 19)\nprint(date)\n\n# Format a date as a string\ndate_string = date.strftime(\"%d-%m-%Y\")\nprint(date_string)<\/code><\/pre>\n\n\n\n<p>There are many modules available in Python&#8217;s standard library that provide a wide range of functionality. Here is a non-exhaustive list of some of the most commonly used modules:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><code>os<\/code> &#8211; provides a way to interact with the operating system, including accessing the file system, environment variables, and system calls.<\/li><li><code>sys<\/code> &#8211; provides access to some variables used or maintained by the Python interpreter and functions that interact strongly with the interpreter.<\/li><li><code>math<\/code> &#8211; provides mathematical functions, including trigonometry, logarithms, and constants like pi.<\/li><li><code>random<\/code> &#8211; provides functions for generating random numbers, choosing random elements from a list, and shuffling sequences randomly.<\/li><li><code>datetime<\/code> &#8211; provides classes for working with dates and times.<\/li><li><code>json<\/code> &#8211; provides functions for encoding and decoding JSON data.<\/li><li><code>csv<\/code> &#8211; provides classes for working with CSV (comma-separated values) files.<\/li><li><code>sqlite3<\/code> &#8211; provides a way to interact with SQLite databases.<\/li><li><code>re<\/code> &#8211; provides support for regular expressions.<\/li><li><code>argparse<\/code> &#8211; provides a way to parse command-line arguments.<\/li><li><code>collections<\/code> &#8211; provides alternative data structures like named tuples, deques, and defaultdicts.<\/li><li><code>urllib<\/code> &#8211; provides functions for working with URLs and URIs.<\/li><li><code>requests<\/code> &#8211; provides an easy-to-use API for making HTTP requests.<\/li><li><code>pickle<\/code> &#8211; provides a way to serialize Python objects into a byte stream.<\/li><li><code>threading<\/code> &#8211; provides classes for working with threads and synchronization primitives like locks and semaphores.<\/li><li><code>logging<\/code> &#8211; provides a way to log messages from your Python code.<\/li><li><code>time<\/code> &#8211; provides functions for working with time, including measuring elapsed time and sleeping.<\/li><li><code>socket<\/code> &#8211; provides a way to work with sockets, including creating client and server applications.<\/li><li><code>subprocess<\/code> &#8211; provides a way to spawn new processes and interact with them.<\/li><li><code>zipfile<\/code> &#8211; provides classes for working with ZIP archives.<\/li><\/ol>\n\n\n\n<p>This is just a small sampling of the many modules available in Python&#8217;s standard library. There are many more modules available for specific purposes, such as scientific computing, web development, and data analysis.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#cdd4d7;font-size:26px\"><strong>22.Type Dispatch<\/strong><\/p>\n\n\n\n<p>Type dispatching in Python refers to the process of dynamically selecting the appropriate implementation of a function or method based on the types of the arguments passed to it at runtime. This is also known as &#8220;runtime polymorphism&#8221; or &#8220;dynamic dispatch&#8221;.<\/p>\n\n\n\n<p>Python provides a built-in mechanism for type dispatching called &#8220;duck typing&#8221;. In Python, the type of an object is determined by its behavior rather than its explicit type. This means that if two objects have the same behavior, they are considered to be of the same type, even if they are not of the same class.<\/p>\n\n\n\n<p>To illustrate this concept, consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def add_numbers(x, y):\n    return x + y\n\nprint(add_numbers(1, 2)) # Output: 3\nprint(add_numbers(1.5, 2.5)) # Output: 4.0\nprint(add_numbers(\"hello\", \"world\")) # Output: helloworld<\/code><\/pre>\n\n\n\n<p>In this example, the <code>add_numbers<\/code> function takes two arguments <code>x<\/code> and <code>y<\/code> and returns their sum. Notice that the function is able to add both integers and floating-point numbers as well as concatenate two strings without any explicit type annotations. This is possible because Python uses duck typing to determine the types of the arguments at runtime and dynamically selects the appropriate implementation of the <code>+<\/code> operator.<\/p>\n\n\n\n<p>Another way to implement type dispatching in Python is through the use of function overloading. Function overloading involves defining multiple functions with the same name but different parameter types or number of parameters. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def add_numbers(x: int, y: int) -&gt; int:\n    return x + y\n\ndef add_numbers(x: float, y: float) -&gt; float:\n    return x + y\n\nprint(add_numbers(1, 2)) # Output: 3\nprint(add_numbers(1.5, 2.5)) # Output: 4.0<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d8dee1;font-size:30px\"><strong>23. Lambda Function<\/strong><\/p>\n\n\n\n<p>A Lambda function in Python is an anonymous function, meaning it is a function without a name, that can be defined and used in a single line of code. Lambda functions are commonly used in functional programming and are often passed as arguments to higher-order functions.<\/p>\n\n\n\n<p>The syntax of a Lambda function in Python is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>lambda arguments: expression<\/code><\/pre>\n\n\n\n<p>Where <code>arguments<\/code> is a comma-separated list of arguments, and <code>expression<\/code> is the operation performed on those arguments. The result of the expression is returned automatically by the function. Here is an example of a Lambda function that returns the sum of two numbers:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>addition = lambda x, y: x + y\nresult = addition(3, 5)\nprint(result) # output : 8<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#cfdade;font-size:30px\"><strong>24. Map Function <\/strong><\/p>\n\n\n\n<p>The <code>map()<\/code> function in Python is a built-in function that applies a specified function to each item of an iterable (e.g. a list, tuple, set) and returns a new iterable object that contains the results.<\/p>\n\n\n\n<p>The basic syntax for the <code>map()<\/code> function is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>map(function, iterable)<\/code><\/pre>\n\n\n\n<p>where <code>function<\/code> is the function to be applied to each item of the <code>iterable<\/code>. <code>iterable<\/code> is the sequence of items to be passed to the function.Here&#8217;s an example of using the <code>map()<\/code> function to apply a function to a list of numbers:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Define a function that squares a number\ndef square(x):\n    return x**2\n\n# Define a list of numbers\nnumbers = &#91;1, 2, 3, 4, 5]\n\n# Apply the square function to each item in the list using map()\nsquared_numbers = map(square, numbers)\n\n# Convert the map object to a list to print the results\nprint(list(squared_numbers))<\/code><\/pre>\n\n\n\n<p>This will output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1, 4, 9, 16, 25]<\/code><\/pre>\n\n\n\n<p>In this example, the <code>square()<\/code> function is applied to each item in the <code>numbers<\/code> list using the <code>map()<\/code> function. The resulting <code>map<\/code> object is then converted to a list and printed. We can also use lambda functions with <code>map()<\/code> to make the code more concise. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Define a list of numbers\nnumbers = &#91;1, 2, 3, 4, 5]\n\n# Apply a lambda function that squares each number to the list using map()\nsquared_numbers = map(lambda x: x**2, numbers)\n\n# Convert the map object to a list to print the results\nprint(list(squared_numbers))\n<\/code><\/pre>\n\n\n\n<p>This will output the same result as before:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1,4,9,16,25]<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dde0e1;font-size:30px\"><strong>25. Filter Function<\/strong><\/p>\n\n\n\n<p>The <code>filter()<\/code> function in Python is a built-in function used for filtering out elements from an iterable based on a given function&#8217;s condition. It returns an iterator that contains the elements from the input iterable that satisfy the given condition.<\/p>\n\n\n\n<p>The syntax of the <code>filter()<\/code> function is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>filter(function, iterable)<\/code><\/pre>\n\n\n\n<p>where:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>function<\/code>: A function that takes a single argument and returns a Boolean value indicating whether the argument satisfies the filter condition.<\/li><li><code>iterable<\/code>: An iterable sequence to be filtered.<\/li><\/ul>\n\n\n\n<p>Here&#8217;s an example that demonstrates how to use the <code>filter()<\/code> function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\ndef is_even(num):\n    return num % 2 == 0\n\neven_numbers = list(filter(is_even, numbers))\n\nprint(even_numbers)\n<\/code><\/pre>\n\n\n\n<p>In this example, we have a list of numbers. We define a function <code>is_even()<\/code> that takes a number as an argument and returns <code>True<\/code> if the number is even, <code>False<\/code> otherwise. We then use the <code>filter()<\/code> function to create a new list called <code>even_numbers<\/code> that contains only the even numbers from the original list of <code>numbers<\/code>.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;2, 4, 6, 8, 10]<\/code><\/pre>\n\n\n\n<p>In this example, the <code>filter()<\/code> function calls the <code>is_even()<\/code> function for each element in the <code>numbers<\/code> list. If the <code>is_even()<\/code> function returns <code>True<\/code>, the element is included in the <code>even_numbers<\/code> list. If it returns <code>False<\/code>, the element is excluded from the <code>even_numbers<\/code> list.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#cad7dd;font-size:30px\"><strong>26. match case <\/strong><\/p>\n\n\n\n<p>The Python <code>match<\/code> statement, introduced in Python 3.10, is a new feature that provides a concise and expressive way to perform pattern matching. It allows you to compare a value against multiple patterns and execute different code blocks based on the matched pattern.<\/p>\n\n\n\n<p>Here&#8217;s an example to illustrate how the <code>match<\/code> statement works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def process_data(data):\r\n    match data:\r\n        case 1:\r\n            print(\"Processing data with value 1\")\r\n        case 2:\r\n            print(\"Processing data with value 2\")\r\n        case _:\r\n            print(\"Processing data with unknown value\")\r\n\r\ndata1 = 1\r\nprocess_data(data1)  # Output: Processing data with value 1\r\n\r\ndata2 = 2\r\nprocess_data(data2)  # Output: Processing data with value 2\r\n\r\ndata3 = 3\r\nprocess_data(data3)  # Output: Processing data with unknown value\r\n<\/code><\/pre>\n\n\n\n<p>In the example above, we define a function called <code>process_data<\/code> that takes a parameter <code>data<\/code>. Inside the function, we use the <code>match<\/code> statement to match the value of <code>data<\/code> against different patterns. <\/p>\n\n\n\n<p>In the first case, if the value of <code>data<\/code> is <code>1<\/code>, the code block under <code>case 1:<\/code> is executed, which prints &#8220;Processing data with value 1&#8221;.<\/p>\n\n\n\n<p>In the second case, if the value of <code>data<\/code> is <code>2<\/code>, the code block under <code>case 2:<\/code> is executed, which prints &#8220;Processing data with value 2&#8221;.<\/p>\n\n\n\n<p>The third case uses <code>_<\/code> as a wildcard pattern, which matches any value. If none of the previous patterns match, the code block under <code>case _:<\/code> is executed, which prints &#8220;Processing data with unknown value&#8221;.<\/p>\n\n\n\n<p>The <code>match<\/code> statement can handle more complex patterns using various match patterns, such as constant patterns, value patterns, sequence patterns, mapping patterns, and more. It offers a powerful way to write more expressive and readable code for handling different cases or conditions.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#c7d2d7;font-size:30px\"><strong>27. List Comprehension<\/strong><\/p>\n\n\n\n<p>List comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each element of an existing iterable (such as a list, tuple, or range) and optionally applying a filter condition.<\/p>\n\n\n\n<p>The basic syntax of list comprehension is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>new_list = &#91;expression for element in iterable if condition]\r<\/code><\/pre>\n\n\n\n<p>Let&#8217;s break down the components:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>expression<\/code>: It represents the operation or transformation to be applied to each element of the iterable. This expression determines what will be included in the new list.<\/li><li><code>element<\/code>: It represents the current element being processed from the iterable.<\/li><li><code>iterable<\/code>: It is the source iterable from which elements are taken to create the new list.<\/li><li><code>condition<\/code> (optional): It is an optional filtering condition that determines whether an element should be included in the new list. Only the elements that satisfy the condition will be included.<\/li><\/ul>\n\n\n\n<p>Here&#8217;s an example to illustrate list comprehension:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Create a new list of squares of numbers from 0 to 9\r\nsquares = &#91;x**2 for x in range(10)]\r\nprint(squares)  # Output: &#91;0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\r<\/code><\/pre>\n\n\n\n<p>In the example above, we use list comprehension to create a new list called <code>squares<\/code>. The expression <code>x**2<\/code> calculates the square of each element <code>x<\/code> from the <code>range(10)<\/code> iterable. Since there is no filtering condition specified, all the elements from 0 to 9 are included in the new list.<\/p>\n\n\n\n<p>List comprehension can also include an <code>if<\/code> condition to filter elements. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Create a new list of even numbers from 0 to 9\r\neven_numbers = &#91;x for x in range(10) if x % 2 == 0]\r\nprint(even_numbers)  # Output: &#91;0, 2, 4, 6, 8]\r<\/code><\/pre>\n\n\n\n<p>In this example, the list comprehension includes the condition <code>x % 2 == 0<\/code>, which filters out odd numbers. Only the even numbers from 0 to 9 are included in the new list.<\/p>\n\n\n\n<p>List comprehension is a powerful feature that allows you to create new lists in a concise and readable way, combining iteration and transformation operations in a single line of code. It can greatly simplify your code when dealing with transformations and filtering of data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Dr.Thyagaraju G S and Palguni G T: A Python cheat sheet is a quick reference guide that summarizes the most important features of the Python programming language. It typically includes&#8230;<\/p>\n","protected":false},"author":1,"featured_media":27329,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":"","_links_to":"","_links_to_target":""},"class_list":["post-23452","page","type-page","status-publish","has-post-thumbnail","hentry"],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/23452","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/comments?post=23452"}],"version-history":[{"count":100,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/23452\/revisions"}],"predecessor-version":[{"id":33267,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/23452\/revisions\/33267"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/media\/27329"}],"wp:attachment":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/media?parent=23452"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}