From bd047ffa25e32a30481f40ef87039a2cf7420e4f Mon Sep 17 00:00:00 2001 From: Ankit Mahato Date: Mon, 24 Oct 2022 14:02:17 +0530 Subject: [PATCH] Update README.md --- README.md | 292 ------------------------------------------------------ 1 file changed, 292 deletions(-) diff --git a/README.md b/README.md index ab95ebe..9c518b3 100644 --- a/README.md +++ b/README.md @@ -449,8 +449,6 @@ Example imaginary literals: 3.5e-10j ``` -#br - ### Points to Note In Python, @@ -458,14 +456,10 @@ In Python, - there is no specialized literal such as a complex literal. A complex number is actually represented in the program using an expression comprising a real number (integer/float numeric literal) and an imaginary number (imaginary literal). For example, `1 + 2j` consists of an integer literal (`1`) and a imaginary literal (`2j`). - numeric literals do not include the minus sign (`-`). `-` is actually a unary operator it combines with a numeric literal to represent negative numbers. For example, in `-3.14` the numeric literal is `3.14` and `-` is an operator. -#br - ## 2. Boolean Literals The reserved words `True` and `False` are also boolean literals which can be used to specify the truth value in a program. -#br - ## 3. String Literals String literals are texts which can be specified in a variety of ways in Python: @@ -516,8 +510,6 @@ E = mc² In the above example, `\u00B2` is the unicode character which represents the 'SUPERSCRIPT TWO'. -#br - ## 4. Special Literal `None` is a special literal which is used to denote the absence of value. @@ -532,8 +524,6 @@ It should not be confused with `0` as `0` is an integer literal with a defined f In the above example, the Python shell does not display any value of `a` as it is assigned as `None` which has no value. -#br - ## 5. Collection of Literals Python has the provision for specifying a collection of literals in the source code using a special syntax known as **"displays"**. @@ -596,8 +586,6 @@ days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satur sum_6 = (1 + 2 + 3 + 4 + 5 + 6) ``` -#br - ## Punctuation, Decoration and Annotation Tokens in Python which are used for punctuation, decoration and annotation are: @@ -607,8 +595,6 @@ Tokens in Python which are used for punctuation, decoration and annotation are: ; @ -> ``` -#br - ## Assignment/Binding The assignment or binding delimiters are used for binding objects to names via assignment statements. The complete list of tokens are provided below: @@ -945,8 +931,6 @@ Each complex number has two parts, the real part which is a numeric integer or f The boolean data type (`bool`) is a subtype of `int`. It stores the evaluated value of expressions represented as keywords - `True` (integer value `1`) and `False` (integer value `0`). -#br - ## 2. Sequence Types An ordered collection of items where each item can be accessed using an integer index is known as a sequence. The following three sequence data types are available in Python: @@ -969,16 +953,12 @@ A `tuple` is an immutable sequence of items of same or different data types whic Some example tuples are - `(1, 2, 3)`, `('abc', 23, 3.14)`, `('edpunk', 'python')`. -#br - ## 3. Set Type A `set` is an unordered collection of unique items of same of different data types which are enclosed in curly braces - `{ }`. Some example sets are - `{1, 2, 3}`, `{'abc', 23, 3.14}`, `{'edpunk', 'python'}`. -#br - ## 4. Mapping Type `dict` is a mapping data type which stores values in the form of key-value pairs. @@ -991,8 +971,6 @@ The key-value pairs are separated by comma (`,`) and enclosed within curly brace Some example dictionaries are - `{1: "a", 2: "b", 3: "c"}`, `{"name": "edpunk", "language": "python"}`. -#br - ## 5. Special Type `None` is a special data type which is used to denote the absence of value in an object. @@ -1055,8 +1033,6 @@ In the below example the final type of `c` is automatically determined as `float ``` -#br - ## Explicit Type Casting When the type conversion is explicitly specified by the user using the various built-in functions available in Python, it is known as explicit type casting. @@ -1444,16 +1420,12 @@ Following are some unary operators available in Python: -6 ``` -#br - ## Binary Operators Binary operators are applied on two operands. For example, arithmetic operators (`+`, `–`, `*`, `/`) evaluate the result of mathematical computation of two values. -#br - ## Operators in Python A rich set of operators are available in Python which can be categorized as follows: @@ -1489,8 +1461,6 @@ In case the operands are of type `str`, `list` or `tuple`, the `+` operator conc ['ed', 'punk', 'python'] ``` -#br - ## Subtraction The `-` operator subtracts the value of operand on right from the value of operand on left. @@ -1500,8 +1470,6 @@ The `-` operator subtracts the value of operand on right from the value of opera -1 ``` -#br - ## Multiplication The `*` operator multiplies the values of numeric operands. @@ -1520,8 +1488,6 @@ In case the operands are of type `str`, `list` or `tuple`, the `*` operator retu ['ed', 'py', 'ed', 'py', 'ed', 'py'] ``` -#br - ## Division The `/` operator divides the value of operand on left by the value of operand on right and returns the real number quotient. @@ -1533,8 +1499,6 @@ The `/` operator divides the value of operand on left by the value of operand on 2.5 ``` -#br - ## Floor Division The `//` operator divides the value of operand on left by the value of operand on right and returns the integer quotient. @@ -1544,8 +1508,6 @@ The `//` operator divides the value of operand on left by the value of operand o 2 ``` -#br - ## Modulus The `%` operator divides the value of operand on left by the value of operand on right and returns the remainder. @@ -1555,8 +1517,6 @@ The `%` operator divides the value of operand on left by the value of operand on 1 ``` -#br - ## Exponent The `**` operator raises the left operand to the power of the right operand. @@ -1598,8 +1558,6 @@ As a sequence is an ordered collection of items, so the order in which the items False ``` -#br - ## Not equal to The `!=` operator returns `True` if the value of operand on left is not equal to the value of operand on right. @@ -1617,8 +1575,6 @@ True False ``` -#br - ## Greater than The `>` operator returns `True` if the value of operand on left is greater than the value of operand on right. @@ -1681,8 +1637,6 @@ If two sequences are of unequal lengths and the smaller sequence is the starting True ``` -#br - ## Greater than or equal to The `>=` operator returns `True` if the value of operand on left is greater than or equal to the value of operand on right. @@ -1709,8 +1663,6 @@ True True ``` -#br - ## Less than The `<` operator returns `True` if the value of operand on left is less than the value of operand on right. @@ -1738,8 +1690,6 @@ True True ``` -#br - ## Less than or equal to The `<=` operator returns `True` if the value of operand on left is lesser than or equal to the value of operand on right. @@ -1790,8 +1740,6 @@ These operators perform the binary operation on the two operands and assign the If `` is a binary operator, then the expression `a = b` containing the augmented assignment operator is equivalent to `a = a b`. -#br - ## += The `+=` operator adds a value (right operand) to the variable (left operand) and assigns the result to that variable. @@ -1808,8 +1756,6 @@ The `+=` operator adds a value (right operand) to the variable (left operand) an 'helloworld' ``` -#br - ## -= The `-=` operator subtracts a value (right operand) from the variable (left operand) and assigns the result to that variable. @@ -1821,8 +1767,6 @@ The `-=` operator subtracts a value (right operand) from the variable (left oper 1 ``` -#br - ## *= The `*=` operator multiplies a value (right operand) to the variable (left operand) and assigns the result to that variable. @@ -1838,8 +1782,6 @@ The `*=` operator multiplies a value (right operand) to the variable (left opera 'hihihi' ``` -#br - ## /= The `/=` operator divides the variable (left operand) by a value (right operand) and assigns the result to that variable. @@ -1851,8 +1793,6 @@ The `/=` operator divides the variable (left operand) by a value (right operand) 2.0 ``` -#br - ## //= The `//=` operator floor divides the variable (left operand) by a value (right operand) and assigns the result to that variable. @@ -1864,8 +1804,6 @@ The `//=` operator floor divides the variable (left operand) by a value (right o 2 ``` -#br - ## **= The `**=` operator raises the variable (left operand) to a power (right operand) and assigns the result to that variable. @@ -1877,8 +1815,6 @@ The `**=` operator raises the variable (left operand) to a power (right operand) 16 ``` -#br - ## %= The `%=` operator computes modulus of the variable (left operand) and a value (right operand) and assigns the result to that variable. @@ -1937,8 +1873,6 @@ True True ``` -#br - ## not The logical state of an operand can be reversed (`False` to `True`, and vice versa) using the logical `not` operator. @@ -1951,8 +1885,6 @@ True False ``` -#br - ## or The logical `or` operator returns `True` if the logical state of any of the two operands is `True`. @@ -1966,8 +1898,6 @@ True False ``` -#br - ## and The logical `and` operator returns `True` if the logical state of both the operands is `True`. @@ -2062,8 +1992,6 @@ Some valid expressions are provided below: As shown above, standalone literals (like `10`) and variables (like `a`) are considered as expressions, but standalone operators are not expressions. -#br - ## Chained Expression Comparison operators can be chained together in Python. @@ -2074,8 +2002,6 @@ For example, `lower <= age <= upper` is a valid chained expression which is equi If `a`, `b`, `c`, …, `y`, `z` are expressions and `op1`, `op2`, …, `opN` are comparison operators, then the chained expression `a op1 b op2 c ... y opN z` is equivalent to `a op1 b and b op2 c and ... y opN z`. -#br - ## Conditional Expression Python does not have ternary operators (`?:`) like other programming languages. Hence, the keywords `if` and `else` are used to create conditional expressions which evaluates to a value based on the given condition. @@ -2118,8 +2044,6 @@ The table below presents the precedence of operators in Python from highest to l | `or` | Boolean `OR` | | `:=` | Assignment expression | -#br - ## Exercise ### Example 1 @@ -2135,8 +2059,6 @@ Step: `*` has higher precedence over `-` = `15 - 8` = `7` -#br - ### Example 2 Evaluate the expression @@ -2150,8 +2072,6 @@ Step: `-` and `+` have the same order of precedence so the expression is evaluat = `13 + 4` = `17` -#br - ### Example 3 Evaluate the expression @@ -2165,8 +2085,6 @@ Parantesized expression `(...)` has the highest precedence so `+` is evaluated f = `15 - 6` = `9` -#br - ### Example 4 Evaluate the expression @@ -2191,8 +2109,6 @@ Evaluate the expression `6 + 2.25 - 2` = `6.25` -#br - ### Example 5 Evaluate the expression @@ -2213,8 +2129,6 @@ Evaluate the expression `4 - 4 + 20` = `20` -#br - ### Example 6 Evaluate the expression @@ -2273,8 +2187,6 @@ Some common syntax errors are: - Incorrect position of keyword - Incorrect block indentation -#br - ## Script Mode When a code containing syntactically incorrect statement is executed using script mode via IDLE, an error dialog box is displayed. @@ -2287,8 +2199,6 @@ On closing the dialog box, the incorrect part of the code, the potential cause o This error has to be rectified to execute the program correctly. -#br - ## Interactive Mode When a syntactically incorrect statement is executed in the Python console (interactive mode), the Python interpreter displays it and also adds a little arrow (`^`) pointing at the entry point or token where the error was detected. @@ -2320,8 +2230,6 @@ Some runtime error examples are: - **TypeError**: Raised while performing an operation on incompatible types. - **IndentationError**: Raised when the indentation of a statement or code block is incorrect. -#br - ## Examples ### ZeroDivisionError @@ -2339,8 +2247,6 @@ Traceback (most recent call last): ZeroDivisionError: division by zero ``` -#br - ### NameError ``` python @@ -2355,8 +2261,6 @@ Traceback (most recent call last): NameError: name 'd' is not defined ``` -#br - ### KeyError ``` python @@ -2371,8 +2275,6 @@ Traceback (most recent call last): KeyError: 3 ``` -#br - ### TypeError ``` python @@ -2542,8 +2444,6 @@ Traceback (most recent call last): ValueError: The value of b cannot be zero ``` -#br - ## assert An `assert` statement is often used during code development to act like a safety valve which notifies the programmer in case the test expression is evaluated as `False`. @@ -2706,8 +2606,6 @@ The control flow view of the above code is: Let us go through some programming problems which utilize selection statements. -#br - ### Absolute Value Write a program to output the magnitude of difference between two numbers using conditional statement. @@ -2734,8 +2632,6 @@ Enter 2nd number: 15 The difference of 12 and 15 is 3 ``` -#br - ### Sorting 3 Numbers Write a program to accept 3 numbers from the user and print them in ascending order of value. @@ -2768,8 +2664,6 @@ Enter 3rd number: 6 The numbers in sorted order: 2 , 6 , 9 ``` -#br - ### Divisibility Write a program to accept two numbers and test if the first number is divisible by the second number. @@ -2811,8 +2705,6 @@ This process can be demonstrated using the below flowchart: Let us go through some code examples to demonstrate how `for` statement can be used to iterate over sequences. -#br - ## List Iteration ### Code @@ -2836,8 +2728,6 @@ BMW Volkswagen ``` -#br - ## Tuple Iteration ### Code @@ -2861,8 +2751,6 @@ BMW Volkswagen ``` -#br - ## String Iteration ### Code @@ -2884,8 +2772,6 @@ o n ``` -#br - ## Range Iteration The `range` type represents an immutable sequence of numbers that is usually used in for loops for looping a certain number of times. `range` object always take the same (small) amount of memory, no matter the size of the range it represents, which is an advantage over a regular `list` or `tuple`. @@ -2925,8 +2811,6 @@ for i in range(5): 20 ``` -#br - ### Example #2 Print all integers from 2 to 5 including the boundary values. @@ -2947,8 +2831,6 @@ for i in range(2, 6): 5 ``` -#br - ### Example #3 Print all odd numbers between 2 and 10. @@ -2977,8 +2859,6 @@ for i in range(2, 10): 9 ``` -#br - ### Example #4 Print the index of all occurrences of `o` in `python programming`. @@ -2999,14 +2879,10 @@ for i in range(len(s)): 9 ``` -#br - ## Exercises Let us go through some programming problems which utilize the `for` iteration statement. -#br - ### Compound Interest Write a program to calculate the total compound interest payable for given principal, interest rate (compounded annually) and total time (in years). @@ -3034,8 +2910,6 @@ Enter the loan duration (in years): 3 Total interest payable: 78812.5 ``` -#br - ### Factorial The factorial of a positive integer `n`, denoted by `n!`, is the product of all positive integers less than or equal to `n`. @@ -3097,14 +2971,10 @@ while i", line 1 SyntaxError: unexpected EOF while parsing ``` -#br - ### 2. Skipping Code Execution `pass` can be used to skip code execution for certain cases. @@ -3247,8 +3113,6 @@ for i in l: 5 is not divisible by 3 ``` -#br - ### Placeholders `pass` can be used to create valid empty functions and classes as placeholders which can be modified in the future versions of code. @@ -3261,8 +3125,6 @@ class EmptyClass: pass ``` -#br - ## break The `break` statement is used to terminate the execution of immediately enclosing `for` or `while` statement. @@ -3305,8 +3167,6 @@ while i <10: 4 ``` -#br - ## continue `continue` statement is used to skip the execution of successive statements and start the next iteration. @@ -3367,8 +3227,6 @@ for n in range(1, 11): 10 ! = 3628800 ``` -#br - ## Nested Loop - break A `break` statement inside the inner loop terminates only the inner loop whereas the outer loop is not affected. @@ -3430,8 +3288,6 @@ multiline String''' ``` -#br - ## Escape Characters The backslash (`\`) character can be used in a string to escape characters that otherwise have a special meaning, such as newline, linefeed, or the quote character. @@ -3451,8 +3307,6 @@ The backslash (`\`) character can be used in a string to escape characters that Although `\'` and `\"` can be used to specify quote characters, Python allows embedding double quotes inside a single-quoted string (`'My name is "Python".'`) and single quotes inside a double-quoted string (`"Python's World"`). -#br - ## Unicode Support Python string objects support Unicode characters. @@ -3466,8 +3320,6 @@ E = mc² In the above example, `\u00B2` is the unicode character which represents the 'SUPERSCRIPT TWO'. -#br - ## Other Types to String In case you want to create a string object from other data types, just use the built-in `str()` function as follows: @@ -3523,8 +3375,6 @@ The built-in function `len()` returns the length of a string which is useful dur We can perform various operations on a string (sequence of characters) such as slicing, membership, concatenation and repetition. -#br - ## Slicing In Python, a character in a string can be easily accessed using its index. @@ -3575,8 +3425,6 @@ The slice operator also allows the usage of a third index which is known as step In the above example, the substring begins at the start of the string, takes a step size of `2` skipping `e` and ends at the last character again skipping the 4th character `l`. -#br - ## Membership `in` and `not in` operators can be used to determine whether a substring is present/not present in a string. @@ -3589,8 +3437,6 @@ True True ``` -#br - ## Concatenation The `+` operator can be used to join two strings. @@ -3604,8 +3450,6 @@ The `+` operator can be used to join two strings. 'HelloWorld' ``` -#br - ## Repetition The `*` operator repeats a string the number of times as specified by the integer operand. @@ -3668,8 +3512,6 @@ For each word present in the string, the first character is uppercased and the r 'Hello Python' ``` -#br - ## 2. Check Characters The following methods are used to check the type of characters in a string. @@ -3774,8 +3616,6 @@ False False ``` -#br - ## 3. Split Methods Split methods help in splitting/partitioning a string. @@ -3813,8 +3653,6 @@ If `maxsplit` is provided, at most `maxsplit` number of splits are performed and ['Hi', 'Ed', 'Punk|v2'] ``` -#br - ## 4. Strip Methods Strip methods are useful in removing leading and/or trailing characters in a string. @@ -3856,8 +3694,6 @@ All leading and trailing characters are removed from the string. 'edpunk' ``` -#br - ## 5. Check Prefix/Suffix `startswith()` and `endswith()` methods are used check whether a string starts or ends with the provided substring (or a tuple of substrings). @@ -3877,8 +3713,6 @@ True True ``` -#br - ## 6. Search/Replace Methods The following string methods are useful for locating substring in a string. @@ -4189,8 +4023,6 @@ False True ``` -#br - ## Concatenation `+` operator can be used to join two lists to create a new list. @@ -4211,8 +4043,6 @@ True ['BMW', 'Z4', 2019, 'Red'] ``` -#br - ## Repetition The `*` operator repeats the items of a list the number of times as specified by the integer operand. @@ -4223,8 +4053,6 @@ The `*` operator repeats the items of a list the number of times as specified by [1, 2, 1, 2, 1, 2] ``` -#br - ## Slicing A subset of list `l` can be obtained using the list slice notation given as `l[i:j]`, where the item at start index `i` is included, but the item at end index `j` is excluded. @@ -4360,8 +4188,6 @@ for i in range(len(l)): 5 True ``` -#br - This method is also useful when you need to modify the items of a list (without altering the length of list) during traversal. For example, let us convert each item of the list into a string. @@ -4383,8 +4209,6 @@ print(l) ['BMW', 'Z4', '2019', '4', 'Red', 'True'] ``` -#br - A `while` statement can be used to traverse a list by iterating on the value of index till the last item index. #### Code @@ -4424,8 +4248,6 @@ Built-in functions `max()`, `min()` and `sum()` are used to calculate the maximu 18 ``` -#br - ## Adding Items `append()` method adds an item (passed as an argument) to the end of a list. @@ -4455,8 +4277,6 @@ If the item has to be added at a particular index, `insert()` method can be used ['T', 'C', 2, 4, 2.5, 'SE'] ``` -#br - ## Locating Items An item `x` can be located in a list using the `index(x[, i[, j]])` method which returns the first occurrence of the item at or after index `i` and before index `j`. @@ -4484,8 +4304,6 @@ In case `i` and `j` are not specified they default to `i=0` and `j=len(l)`. 2 ``` -#br - ## Removing Items `clear()` method removes all items from the list. @@ -4524,8 +4342,6 @@ If an index is provided, `pop()` method removes the item at that index, else the ['T', 'C', 4, 'S'] ``` -#br - ## Reversing Items `reverse()` method can be used to reverse a list in-place. @@ -4548,8 +4364,6 @@ If you do not wish to modify the existing list and create a new list with items ['T', 'C', 2, 4, 'S'] ``` -#br - ## Sorting Items Python lists have a built-in `sort()` method which sorts the items in-place using `<` comparisons between items. @@ -4804,8 +4618,6 @@ Maximum : 9.0 Mean : 4.2 ``` -#br - ## Linear Search Write a program to enter a list and then check if the number entered by a user is present in that list. @@ -4855,8 +4667,6 @@ Enter search value: 1 Search value not found ``` -#br - ## Frequency of Elements Write a program to enter a list and then print the frequency of elements present in that list. @@ -5088,8 +4898,6 @@ False True ``` -#br - ## Concatenation `+` operator can be used to join two tuples to create a new tuple. @@ -5101,8 +4909,6 @@ True ('BMW', 'Z4', 2019, 'Red') ``` -#br - ## Repetition The `*` operator creates a new tuple with items of a tuple repeated the number of times as specified by the integer operand. @@ -5113,8 +4919,6 @@ The `*` operator creates a new tuple with items of a tuple repeated the number o (1, 2, 1, 2, 1, 2) ``` -#br - ## Tuple Slicing A subset of tuple `t` can be obtained using the tuple slice notation given as `t[i:j]`, where the item at index `i` is included, but the item at index `j` is excluded. @@ -5192,8 +4996,6 @@ Red True ``` -#br - ## Location or Index Based Traversal In location based or index based traversal the value of index starts at `0` and increments as long as it is lesser than the length of the tuple. @@ -5222,8 +5024,6 @@ Red True ``` -#br - A `while` statement can be used to traverse a tuple by iterating on the value of index. #### Code @@ -5447,8 +5247,6 @@ A sequence of `key: value` pairs separated by commas in braces - `{}`. {'yr': 20, 'name': 'Ed', 18: True} ``` -#br - ## Sequence of (key, value) Tuples A sequence of (key, value) tuples can be passed as an argument to the `dict()` function. @@ -5461,8 +5259,6 @@ A sequence of (key, value) tuples can be passed as an argument to the `dict()` f {'yr': 20, 'name': 'Ed', 18: True} ``` -#br - ## Keyword/Named Arguments Keys and values can be passed as keyword arguments to the `dict()` function. @@ -5476,8 +5272,6 @@ Keys and values can be passed as keyword arguments to the `dict()` function. One of the limitations of this method is that the keys of the dictionary are only of type string and their names must be within the namespace of an identifier. -#br - ## Key and Value Lists There might cases when there is a need to combine two lists where keys are in one list and the corresponding values are available in another list. @@ -5495,8 +5289,6 @@ The zipped iterator can be passed as an argument to the `dict()` to create a new {'yr': 20, 'name': 'Ed', 18: True} ``` -#br - ## Keys with Default Value `dict.fromkeys(iterable[, value])` can be used to create new dictionary with items of an `iterable` as keys with an optional value (default - `None`) corresponding to the keys. @@ -5521,8 +5313,6 @@ The zipped iterator can be passed as an argument to the `dict()` to create a new 20 ``` -#br - ## get() `get(key[, default])` method can also be used to fetch the value for a key if key is in the dictionary, else a `default` value is returned. @@ -5560,8 +5350,6 @@ In case key `x` already exists, assignment updates or overwrites the value corre {'yr': 20, 18: True, 'name': 'Py'} ``` -#br - ## update() `update()` method can be used to add new items or update existing items in a `dict`. @@ -5581,8 +5369,6 @@ This method accepts the following: {'yr': 15, 18: False, 'name': 'Ed'} ``` -#br - ### 2. Sequence of (key, value) pairs ``` python @@ -5593,8 +5379,6 @@ This method accepts the following: {'yr': 15, 18: True, 'name': 'Ed'} ``` -#br - ### 3. Keyworded arguments ``` python @@ -5604,8 +5388,6 @@ This method accepts the following: {'yr': 15, 18: True, 'name': 'Ed'} ``` -#br - ## setdefault() `setdefault(key[, default])` method returns a value corresponding to a key. @@ -5640,8 +5422,6 @@ If no default value is provided, the value is set as `None`. {'yr': 20, 18: True} ``` -#br - ## clear() `clear()` method can be used to clear all values of a dictionary. @@ -5654,8 +5434,6 @@ If no default value is provided, the value is set as `None`. {} ``` -#br - ## pop() `pop(key[, default])` method can be used to remove a `key: value` pair. @@ -5679,8 +5457,6 @@ KeyError: 'name' 'Punk' ``` -#br - ## popitem() `popitem()` can be used to destructively iterate over a dictionary removing and returning a `(key, value)` pair in LIFO (Last Item First Out) order. @@ -5721,8 +5497,6 @@ Similarly, `not in` can be used to determine the absence of a `key`. True ``` -#br - ## Union The `|` (union) operator can be used to merge two dictionaries. @@ -5767,8 +5541,6 @@ name : Ed 18 : True ``` -#br - ## Traversing Using Dictionary Methods Dictionary methods `items()`, `keys()` and `values()` can be used to fetch the items, keys and values in a dictionary, respectively. @@ -5803,8 +5575,6 @@ name 18 ``` -#br - #### Code ``` python @@ -5822,8 +5592,6 @@ Ed True ``` -#br - #### Code ``` python @@ -5853,8 +5621,6 @@ name : Ed 3 ``` -#br - ## Min and Max The `min()` and `max()` built-in functions return the minimum and maximum value among the keys of a dictionary. @@ -5876,8 +5642,6 @@ In case of string keys, they return the first and last occurring strings alphabe 3 ``` -#br - ## Copy A new copy of a dictionary can be made using `copy()` method: @@ -5958,8 +5722,6 @@ d - 1 a - 2 ``` -#br - ## Salary Book Write a program to enter employee names and their salaries as input and store them in a dictionary. @@ -6164,8 +5926,6 @@ Enter name: Python Hello, Python ``` -#br - ## print() The built-in `print()` function can be used to display an output (value of variables, expressions, etc.) on the standard output. @@ -6187,12 +5947,8 @@ print("Area:", area) Area: 50 ``` -#br - Both, `input()` and `print()` functions are covered in detail in the chapter **Input & Output**. -#br - ## open() `open()` function is used to open a file and return the corresponding file object. @@ -6314,8 +6070,6 @@ The following frequently used mathematical constants are available in `math` mod 6.283185307179586 ``` -#br - ## Functions Following useful mathematical functions are available in the `math` module: @@ -6563,8 +6317,6 @@ It can either be an absolute path or a relative path as shown below: - `'../fname.txt'` is the relative path of a text file outside the current directory where the python script is being executed. - `'/Users/edpunk/Documents/fname.txt'` is the absolute path of a text file which can be opened by the python script from any location as long as it is in the same system. -#br - ### mode `mode` is an optional string parameter which specifies the mode in which the file has to be opened. It defaults to `'r'` which means open for reading in text mode. @@ -6587,8 +6339,6 @@ The available modes are: - `'a+'` : Opens the file in read and append mode. It creates a new file if it does not exist. If the file already exists, new data is automatically added at the end of the file after existing data. - `'a+b'` : Opens the file in binary read and append mode. -#br - After opening a file and performing some file operations, it can be safely closed using the `close()` method. For example, let us write a program to open a file `data.txt` in read and append mode and close the file object in the successive statement. @@ -6637,8 +6387,6 @@ Thank You >>> f.close() ``` -#br - ### readline() `readline(size = -1)` method without any arguments is used to read and return one line at a time from the given file. @@ -6673,8 +6421,6 @@ Thank You >>> f.close() ``` -#br - Since `readline()` returns one row at a time, it can be used in a `while` statement to iterate over the data row-wise. Once it reaches the end of file it returns an empty string. #### Code @@ -6702,8 +6448,6 @@ Hello World Thank You ``` -#br - `for` statement can also be used to traverse the file row-wise without any requirement of the `readline()` method. Simply iterating over the file object returns the data one row at a time. #### Code @@ -6726,8 +6470,6 @@ Hello World Thank You ``` -#br - ### readlines() `readlines()` method returns a list of strings representing the lines (along with the newline character) of text file content. @@ -6749,8 +6491,6 @@ Thank You ['Hello World\n', 'Thank You'] ``` -#br - ## 2. Random Access The following two methods can be used on a file object to randomly access contents of a file: @@ -6769,8 +6509,6 @@ Let us consider the same file `info.txt` for the below example: 4 ``` -#br - ### seek() `seek(offset, reference=0)` can be used to seek a location in the file object which is `offset` bytes from the provided `reference`. @@ -6893,8 +6631,6 @@ where: >>> f.close() ``` -#br - ## Loading Data The `load()` function can be used to read the pickled representation of an object or data from a file. @@ -6912,8 +6648,6 @@ where `file` is an open file object (opened in binary read mode `rb`). [['Anita', 'Maths', 83], ['Amar', 'Maths', 95], ['Ani', 'Maths', 90]] ``` -#br - ## Example: Traversing a Binary File Write a program which performs the following Record Keeping activities: @@ -7085,8 +6819,6 @@ with open('marks.csv', ['Ira', 'Science', '99.0'] ``` -#br - ### Example 2 Let us write a program to read the contents of `marks2.csv`. @@ -7126,8 +6858,6 @@ with open('marks2.csv', ['Ira', 'Physics|Chemistry|Biology', '99.0'] ``` -#br - ## Writing CSV File `csv.writer(csvfile, delimiter=',', quotechar='"')` function returns a writer object which converts data in form of a list into delimited strings which is passed down to the file object for writing. @@ -7165,8 +6895,6 @@ with open('marks.csv', 'w', writer.writerow(row) ``` -#br - #### Solution #2: Using writerows() ``` python @@ -7191,8 +6919,6 @@ with open('marks.csv', 'w', writer.writerows(marks) ``` -#br - #### Output - marks.csv ``` @@ -7230,8 +6956,6 @@ def adder(f, s, t = None): return s ``` -#br - ## Function Header ``` python @@ -7248,8 +6972,6 @@ In case any parameters are required by the function, they are enclosed inside th Finally, the function header ends with a colon. -#br - ## Function Body The body of the function consists of one or more Python statements which have the same amount of indentation (4 spaces) from the function header. @@ -7396,8 +7118,6 @@ tres() 30 ``` -#br - In case a variable is defined inside a function with the same name as that of a global variable, then the variable is considered as a local variable and all references made to the variable point to this local variable. #### Code @@ -7427,8 +7147,6 @@ tres() 30 ``` -#br - Any changes made to a global variable inside a code block or a function can modify it for that session. This can have an impact on all the code blocks/functions that access and use it. To modify the value of a global variable one can use the `global` keyword as shown in the example below. @@ -7487,8 +7205,6 @@ print(l) [2, 4, 6] ``` -#br - ## Dictionary #### Code @@ -7575,8 +7291,6 @@ print(st) 60 ``` -#br - The `as` keyword can also be used to create an alias which makes it easier and more manageable to use in the program. #### Code @@ -7596,8 +7310,6 @@ print(st) 60 ``` -#br - Instead of loading all the functions in a module, the `from` statement can be used to access only specified functions. #### Code @@ -7614,8 +7326,6 @@ print(sa) 40 ``` -#br - To import all functions and global variables in the module the `*` wildcard character can be used. #### Code @@ -7633,8 +7343,6 @@ st = tripler(20) 60 ``` -#br - The above method of using `*` to import the contents of a module is not recommended as it can clutter the namespace and cause issues if there are conflicts between the identifiers defined by the programmer and those defined in the module/package. # Executable Scripts/Modules