├── .github └── ISSUE_TEMPLATE │ └── feature_request.md ├── Built-in-datatypes ├── Dictionary │ └── ReadMe.md ├── Lists │ └── ReadMe.md ├── Strings │ └── ReadMe.md └── Tuples │ └── ReadMe.md ├── CODE_OF_CONDUCT.md ├── Classes ├── Class_Variables.md ├── Classes_and_Instances.md ├── Inheritance.md ├── exampleProgram.md └── typesOfMethods.md ├── Contributing.md ├── Functions ├── 1_Introduction_to_Functions.md ├── 2_BuiltIn_&_Composition_Functions.md └── 3_Lambda_Expressions.md ├── LICENSE ├── Learn to handle your file ├── Introduction.md ├── Reading from a file.md └── writing to a file.md └── README.md /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /Built-in-datatypes/Dictionary/ReadMe.md: -------------------------------------------------------------------------------- 1 | :no_entry_sign: **WORK IN PROGRESS** :no_entry_sign: 2 | 3 | # Dictionary 4 | ### What is a dictionary?:books: 5 | Let's assume u wanna lookup the meaning of a particular word. What do you do? You open up your dictionary!! You try to figure where this word lies by having a vague idea about its lexicographic position and try to find it. Once you find the word "Hooray!!", now all you got to do is read the meaning written beside it.

6 | That's how conventional dictionaries work. You have a key, which is the word itself and a value which is the meaning of the word you were searching for. So basically you were using the word (key) as a way of finding the meaning (value). Hence we can say that the dictionary in real life is a huge collection of word-meaning pair (key-value pair), in which we are using the word as the means of accessing the meaning. Turns out that's more or less what dictionaries in python are too! It is a collection of key-value pairs in which keys are used to access the values. 7 | 8 | ### Let's create a dictionary in python 9 | 10 | Now let's create our own dictionary, and let's keep a name for it. Just like Cambridge has one dictionary oxford another, We are going to create a new dictionary with the name my_dict. The syntax for doing the same is as follows: 11 | ```python 12 | my_dict={} 13 | ``` 14 | What this piece of code does in python is create a new empty dictionary, with the name my_dict. Anytime we want to access something from the dictionary or write something from the dictionary we use the name of the dictionary first and then continue.
15 | Now I want to add word-meaning pairs to it. For that, all I have to do is: 16 | ```python 17 | my_dict['truth']='the quality or state of being true.' 18 | ``` 19 | What we are doing here is we are defining the meaning for a word 'truth' and adding it to the dictionary. Since we use the word to access the meaning the information is also stored in a similar manner. The meaning of the word 'truth' can be accessed by the key truth from the dictionary my_dict. Hence the genral syntax follows: 20 | ```python 21 | dict_name[key]=value 22 | ``` 23 | -------------------------------------------------------------------------------- /Built-in-datatypes/Lists/ReadMe.md: -------------------------------------------------------------------------------- 1 | **Author:** Diya Maria Deepak 2 | 3 | **Edits:** S Sandeep Pillai, Ashley T Roy 4 | 5 | *** 6 | 7 | # Lists 8 | 9 | * Lists are a collection which is ordered and changeable. 10 | * It can contain different data types. 11 | * Lists are written within square brackets. 12 | * They also allow duplicate elements. 13 | 14 | # List Declaration 15 | 16 | ## Empty list 17 | An empty list is declared using square brackets. 18 | ```python 19 | l=[] 20 | ``` 21 | ## List with values 22 | Values can be given to the list during declaration by separating the elements with commas. 23 | ```python 24 | l=[12,23.2,"abc",12] 25 | ``` 26 | ## List declaration using type constructor 27 | ```python 28 | list(values) 29 | ``` 30 | ## List declaration through iterations 31 | ```python 32 | [x for x in iterable] 33 | ``` 34 | Example: 35 | ```python 36 | a=[x for x in range(2)] 37 | ``` 38 | Here, `a=[0,1]`. 39 | 40 | # Nested Lists 41 | A list can even have another list as an element. This is called a nested list. 42 | ```python 43 | # nested list 44 | my_list = ["mouse", [8, 4, 6], ['a']] 45 | ``` 46 | # List Indexing 47 | 48 | All elements in the list are ordered from 0 to n-1 where n is the number of elements in the list. 49 | 50 | In the above example: 51 | ```python 52 | l[0]=12 53 | l[1]=23.2 54 | l[2]="abc" 55 | l[3]=12 56 | ``` 57 | 58 | Trying to access an element other than 0 to 3 indices will raise an `IndexError` and not providing an integer value as the index will create a `TypeError`. 59 | 60 | ## Negative Indexing 61 | The index of -1 refers to the last item, -2 to the second last item and so on. 62 | 63 | Example: 64 | `l=[1,2,3,4,5]`. 65 | Here, `l[-1]` is `5` and `l[-2]` is `4`. 66 | 67 | ## Indexing for nested lists 68 | We use nested indexing in such cases. 69 | 70 | Example: `l=[1,[2,3,4],6,[4,8,12]]`. Here, 71 | 72 | ```python 73 | l[0]=1 74 | l[1]=[2,3,4] 75 | l[1][0]=2 76 | l[1][1]=3 77 | l[1][2]=4 78 | l[2]=6 79 | l[3]=[4,8,12] 80 | l[3][0]=4 81 | l[3][1]=8 82 | l[3][2]=12 83 | ``` 84 | # Slice Operator 85 | 86 | Slice operation is used to access a specified range of elements in a list. 87 | 88 | General syntax: `list_name[start:stop:step]` 89 | 90 | * **Start** - starting integer where the slicing of the object starts. 91 | * **Stop** - integer until which the slicing takes place. The slicing stops at index stop - 1. 92 | * **Step** (optional) - integer value which determines the increment between each index for slicing. By default, this value is 1. 93 | 94 | If no value is given for start and stop, it considers the beginning and the end of the list respectively. 95 | 96 | Examples: 97 | 98 | 1. Input: `print(l[2:5])` 99 | 100 | Output: `[3,4,5]` 101 | 102 | 2. Input: `print(l[:3])` 103 | 104 | Output: `[1,2,3]` 105 | 3. Input: `print(l[2:])` 106 | 107 | Output: `[3,4,5]` 108 | 109 | # Adding elements into an already existing list 110 | 111 | ## Append function 112 | `append()` adds an element to end of the list. 113 | 114 | Syntax: `list_name.append(value)` 115 | 116 | Example: 117 | ```python 118 | l=[1,2,3] 119 | n=[4,5] 120 | l.append(n) 121 | ``` 122 | Now, `l=[1,2,3,[4,5]]` 123 | 124 | This function adds only ***one element*** to the list at a time. 125 | 126 | ## Extend function 127 | `extend()` adds multiple elements to the end of the list. 128 | 129 | Syntax: `list_name.extend(values)` 130 | 131 | Example: 132 | ```python 133 | l=[1,2,3] 134 | n=[4,5] 135 | l.extend(n) 136 | ``` 137 | Now, `l=[1,2,3,4,5]`. 138 | 139 | **Note:** Only one argument can be given for `extend()`. 140 | 141 | ## + Operator 142 | `+` is used to concatenate 2 lists. 143 | 144 | Example: 145 | ```python 146 | l=[1,2] 147 | n=[3,4,5] 148 | x=l+n 149 | ``` 150 | Here, `x=[1,2,3,4,5]` 151 | 152 | ## Insert function 153 | 154 | `insert()` is used to add an element at the given index. 155 | 156 | Syntax: `list_name.insert(index,value)` 157 | 158 | Example: 159 | ```python 160 | l=[1,2,3] 161 | l.insert(1,10) 162 | ``` 163 | Now, `l=[1,10,2,3]`. 164 | 165 | # Deleting elements from a list 166 | 167 | ## Del function 168 | 169 | Syntax: `del(list_name[index])` 170 | 171 | Example: 172 | ```python 173 | l=[1,2,3,4] 174 | del(l[2]) 175 | ``` 176 | Now, `l=[1,2,4]` 177 | 178 | Multiple elements can be deleted using `del()` by slicing. 179 | 180 | Example: 181 | ```python 182 | l=[1,2,3,4,5,6] 183 | del(l[1:4]) 184 | ``` 185 | Now, `l=[1,5,6]`. 186 | 187 | ## Remove function 188 | `remove()` is used when the index is unknown. 189 | 190 | Syntax: `list_name.remove(value)` 191 | 192 | Example: 193 | ```python 194 | l=[1,2,3,4,3] 195 | l.remove(3) 196 | ``` 197 | Now, `l=[1,2,4,3]` since only the first occurence of the element is considered. 198 | 199 | ## Pop function 200 | `pop()` returns and removes the last element of the list. 201 | 202 | Syntax: `list_name.pop()` 203 | 204 | Example: 205 | ```python 206 | l=[1,2,3,4,5] 207 | l.pop() 208 | ``` 209 | Here, `5` is returned and `l=[1,2,3,4]`. 210 | 211 | An index can also be given in the parentheses to remove a specific element in the list. 212 | 213 | # Other Functions 214 | 215 | ## Len function 216 | `len()` returns the length of the list. 217 | 218 | Example: 219 | ```python 220 | l=[1,2,3,4] 221 | print(len(l)) 222 | ``` 223 | Output: `4` 224 | 225 | ## Reverse function 226 | `reverse()` is used to reverse the order of elements in the list and this function does not return anything. 227 | 228 | Syntax: `list_name.reverse()` 229 | 230 | Example: 231 | ```python 232 | l=[1,2,3,4] 233 | l.reverse() 234 | ``` 235 | Now, `l=[4,3,2,1]`. 236 | 237 | ## Sort function 238 | `sort()` is used to sort the elements in the list in ascending order or alphabetical order in case of integers and strings respectively. 239 | This function will not work if integer/float and string values are present in the list to be sorted. 240 | 241 | Syntax: `list_name.sort()` 242 | 243 | Example: 244 | ```python 245 | l=[8,12,36,29,4] 246 | l.sort() 247 | ``` 248 | Now, `l=[4,8,12,29,36]`. 249 | 250 | For sorting in descending order, we use the following syntax: 251 | ```python 252 | list_name.sort(reverse=True) 253 | ``` 254 | 255 | **NOTE: The sort() function is NOT the same as the sorted() function. sort() is a subfunction of list datatype which `CANNOT` be used for other data types such as tuples or dictionaries.** 256 | 257 | ` 258 | 259 | ## Max and min functions 260 | `max()` and `min()` functions return the maximum and minimum values in the list respectively. 261 | 262 | Syntax: `max(list_name)` 263 | 264 | Example: 265 | ```python 266 | l=[5,6,3,8,1,9] 267 | print(max(l)) 268 | ``` 269 | Output: `9` 270 | 271 | ## Count function 272 | `count()` returns the number of occurrences of the given value in the list. 273 | 274 | Synatx: `list_name.count(value)` 275 | 276 | Example: 277 | ```python 278 | l=[1,4,2,8,4,1,8,9,8] 279 | print(l.count(8)) 280 | ``` 281 | Output: `3` 282 | 283 | ## Index function 284 | 285 | `index()` returns the index of the given value. 286 | 287 | Syntax: `list_name.index()` 288 | 289 | Example: 290 | ```python 291 | l=[1,2,3,4,5,6] 292 | print(l.index(4)) 293 | ``` 294 | Output: `3` 295 | 296 | In case of multiple occurrences of a value, the first occurrence is considered. 297 | 298 | *** 299 | -------------------------------------------------------------------------------- /Built-in-datatypes/Strings/ReadMe.md: -------------------------------------------------------------------------------- 1 | **Author:** [vhawk19](www.github.com/vhawk19)
2 | **Editor(s):** [Emmanuel Antony](https://github.com/emmanuelantony2000) 3 | 4 | 5 | # String 6 | 7 | * Textual data in python is handled by str objects(strings) 8 | * They are immutable sequences of Unicode code points. 9 | They can be written in a variety of ways 10 | ```python 11 | # Single quotes 12 | 'allows embedded double quotes like these "" ' 13 | 'Bob asked me, "Do you believe in unicorns?"' 14 | 15 | # Double quotes 16 | "allows embedded single quotes like these '' " 17 | "I'm going fishing someday!" 18 | 19 | #triple Double/Single quote, these can span across multiple lines(all associated whitesapce characters will be included in the string) 20 | '''tripled single quote which allows for embedded double quotes''' 21 | """tripled double quotes which allow for embedded single quotes""" 22 | String literals in python are surrounded by either single quotation marks or double quotation marks. 23 | 24 | ``` 25 | * Strings may be constructed from other objects using the **str** function 26 | ```python 27 | a = str(10) 28 | #here a is nothing but a string "10"/'10' 29 | ``` 30 | 31 | Strings can be output to screen using the print function. For example: print("hello"). 32 | 33 | Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. 34 | 35 | ```python 36 | a = "this is a string" 37 | ``` 38 | 39 | ## Printing String Literals 40 | 41 | String literals can be printed using the print function. 42 | 43 | Use `' '` **single quotes** or `" "` **double quotes** for single line printing and `''' '''` **three single quotes** for multi-line printing. 44 | ```python 45 | print('Hello World') 46 | print("Hello World") 47 | print('Hello\nWorld') 48 | print('''Hello 49 | World''') 50 | ``` 51 | Output: 52 | ``` 53 | Hello World 54 | Hello World 55 | Hello 56 | World 57 | Hello 58 | World 59 | ``` 60 | 61 | ## String Functions 62 | 63 | We can use some arithmetic operators with string for some manipulation with it. 64 | Arithmetic operators such as **+** or **\*** can be used for concatenation or repitition respectively. 65 | For concatenation both operands should be string literals and for repitition one should be a string literal and the other should be an integer literal. 66 | For repition where the operands are different, the order of operands doesn't matter 67 | ```python 68 | a = 'a' 69 | b = 'b' 70 | print(a+b) 71 | print(a+str(5)) #for concatenating numbers str() function has to be used so as to convert the integer to a string literal 72 | print(a*5) 73 | print(5*b) 74 | print(2*a*2) 75 | print(2*2*b) 76 | ``` 77 | Output: 78 | ``` 79 | ab 80 | a5 81 | aaaaa 82 | bbbbb 83 | aaaa 84 | bbbb 85 | ``` 86 | We can use `[ ]` **square brackets** to get a substring of a string. 87 | The format is `[a:b]` where a and b are the indices, a is inclusive while b is exclusive. 88 | ```python 89 | s = 'Hello World' 90 | print(s[1:3]) 91 | print(s[:4]) 92 | print(s[2:]) 93 | print(s[:]) 94 | ``` 95 | Output: 96 | ``` 97 | el 98 | Hell 99 | llo World 100 | Hello World 101 | ``` 102 | There is an optional parameter which we can specify inside the `[ ]` which specifies which characters to take and in what direction, like an increment parameter, the default value of it being 1 (little difficult to understand, please see the examples). 103 | ```python 104 | s = 'Hello World' 105 | print(s[::1]) #Same as the original string 106 | print(s[::2]) #Will take every second character in the string 107 | print(s[::5]) #Will take every fifth character 108 | print(s[3::3]) #Will take every third character in the substring s[3:] 109 | ``` 110 | Output: 111 | ```python 112 | Hello World 113 | HloWrd 114 | H d 115 | lWl 116 | ``` 117 | Now, after mastering this, reversing a string can be tackled very easily. 118 | 119 | ```python 120 | s = 'I like Computers' 121 | print(s[::-1]) #The string is read in reverse order due to the negative sign 122 | ``` 123 | Output: 124 | ```python 125 | sretupmoC ekil I 126 | ``` 127 | 128 | ## String Methods 129 | 130 | ### str.capitalize() 131 | Return a copy of the string with its first character capitalized and the rest lowercased. 132 | 133 | ```python 134 | a = "lorem ipsum dolor sit amet" 135 | a.capitalize() 136 | print(a) 137 | #Output: Lorem ipsum dolor sit amet 138 | ``` 139 | ### str.center(width[, fillchar]) 140 | Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if the width is less than or equal to len(s). 141 | 142 | ```python 143 | a = "lorem ipsum dolor sit amet" 144 | a.center(40," ") 145 | #Output:' lorem ipsum dolor sit amet ' 146 | a.center(40,"*") 147 | #Output:'*******lorem ipsum dolor sit amet*******' 148 | ``` 149 | ### str.count(sub[,start[,end]]) 150 | Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. 151 | 152 | ```python 153 | a = "lorem ipsum dolor sit amet" 154 | a.count('i') 155 | #Output:2 156 | a.count('i',7) 157 | #Output:1 158 | a.count('i',7,9) 159 | #Output:0 160 | ``` 161 | ### str.endswith(suffix[,start[,end]]) 162 | Return True if the string ends with the specified suffix, otherwise return False. Suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. 163 | 164 | ```python 165 | a = 'lorem ipsum dolor sit amet' 166 | a.endswith('amet') 167 | #Output:True 168 | a.endswith('dolor') 169 | #Output:False 170 | a.endswith('amet',1) 171 | #Output: True 172 | a.endswith('amet',1,2) 173 | #Output:False 174 | ``` 175 | ### str.find(sub[, start[, end]]) 176 | 177 | Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. 178 | 179 | ```python 180 | a = "lorem ipsum dolor sit amet" 181 | a.find("ipsum") 182 | #Output:6 183 | a.find("ipsum",7) 184 | #Output:-1 185 | a.find("ipsum",7,10) 186 | #Output:-1 187 | ``` 188 | ### str.format(\*args,\*\*kwargs) 189 | Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument. 190 | ```python 191 | a = "lorem ipsum dolor sit amet is {0}" 192 | a.format(1+2) 193 | #Output:'lorem ipsum dolor sit amet is 3' 194 | ``` 195 | ### str.isalpha() 196 | Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard. 197 | ```python 198 | a = "lorem ipsum dolor sit amet" 199 | a.isalpha() 200 | #Output:True 201 | ``` 202 | ### str.isalnum() 203 | Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric(). 204 | ```python 205 | a = "lorem ipsum dolor sit amet" 206 | a.isalnum() 207 | #Output:True 208 | ``` 209 | ### str.isdecimal() 210 | Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”. 211 | 212 | ```python 213 | a = "lorem ipsum dolor sit amet" 214 | a.isdecimal() 215 | #Output:False 216 | ``` 217 | ### str.isdigit() 218 | Return true if all characters in the string are digits and there is at least one character, false otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type = Digit or Numeric_Type = Decimal. 219 | 220 | ```python 221 | a = "lorem ipsum dolor sit amet" 222 | a.isdigit() 223 | #Output:False 224 | ``` 225 | 226 | ### str.islower() 227 | Return true if all cased characters [4] in the string are lowercase and there is at least one cased character, false otherwise. 228 | 229 | ```python 230 | a = "lorem ipsum dolor sit amet" 231 | a.islower() 232 | #Output:True 233 | ``` 234 | ### str.isspace() 235 | Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. Whitespace characters are those characters defined in the Unicode character database as “Other” or “Separator” and those with the bidirectional property being one of “WS”, “B”, or “S”. 236 | 237 | ```python 238 | a = "lorem ipsum dolor sit amet" 239 | a.isspace() 240 | #Output:False 241 | ``` 242 | ### str.istitle() 243 | Return true if the string is a titlecased string and there is at least one character, for example, uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise. 244 | ```python 245 | a = "lorem ipsum dolor sit amet" 246 | a.istitle() 247 | #Output:False 248 | ``` 249 | ### str.isupper() 250 | Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise. 251 | ```python 252 | a = "lorem ipsum dolor sit amet" 253 | a.isupper() 254 | #Output:False 255 | ``` 256 | 257 | ### str.join(iterable) 258 | Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method. 259 | 260 | ```python 261 | a = "lorem ipsum" 262 | b = ['1','2','3','4'] 263 | a.join(b) 264 | #Output:'1lorem ipsum2lorem ipsum3lorem ipsum4' 265 | ``` 266 | ### str.ljust(width[, fillchar]) 267 | Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s). 268 | 269 | ```python 270 | a = "lorem ipsum" 271 | a.ljust(40,'*') 272 | #Output:'lorem ipsum*****************************' 273 | ``` 274 | 275 | ### str.lower() 276 | Return a copy of the string with all the cased characters converted to lowercase 277 | ```python 278 | a = "LOREM IPSUM" 279 | a.lower() 280 | #Output:'lorem ipsum' 281 | ``` 282 | ### str.lstrip([chars]) 283 | Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped: 284 | 285 | ```python 286 | a = ' lorem ipsum' 287 | a.lstrip() 288 | #Output:lorem ipsum 289 | a = 'lorem ipsum' 290 | a.lstrip('lo') 291 | #Output:rem ipsum 292 | a = 'abababcfghasab' 293 | a.lstrip('ab') 294 | #Output:cfghasab All patterns of the given substring till another pattern is found will be stripped away starting from the left 295 | ``` 296 | 297 | ### str.partition(sep) 298 | Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings. 299 | ```python 300 | a = 'lorem ipsum' 301 | a.partition(' ') 302 | #Output:('lorem', ' ', 'ipsum') 303 | ``` 304 | ### str.replace(old,new[,count]) 305 | Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. 306 | 307 | ```python 308 | a = 'lorem ipsum' 309 | a.replace('l','u') 310 | #Output:'uorem ipsum' 311 | ``` 312 | 313 | ### str.rjust(width[ ,fillchar]) 314 | Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if the width is less than or equal to len(s). 315 | 316 | ```python 317 | a = 'lorem ipsum' 318 | a.rjust(40,'*') 319 | #Output:'*****************************lorem ipsum' 320 | ``` 321 | ### str.split(sep = None,maxsplit = -1) 322 | Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). 323 | 324 | ```python 325 | a = 'lorem ipsum' 326 | a.split() 327 | #Output:['lorem', 'ipsum'] 328 | ``` 329 | 330 | ### str.splitlines([keepends]) 331 | Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. 332 | 333 | ```python 334 | a = '''lorem 335 | ipsum''' 336 | a.splitlines() 337 | #Output:['lorem', 'ipsum'] 338 | ``` 339 | ### str.startswith(prefix[, start[, end]]) 340 | Return True if the string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. 341 | 342 | ```python 343 | a = 'lorem ipsum' 344 | a.startswith('lorem') 345 | #Output:True 346 | ``` 347 | ### str.title() 348 | Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase. 349 | ```python 350 | a = 'lorem ipsum' 351 | a.title() 352 | #Output:'Lorem Ipsum' 353 | ``` 354 | ### str.upper() 355 | return a copy of the string with all the cased characters converted to uppercase. 356 | 357 | ```python 358 | a = 'lorem ipsum' 359 | a.upper() 360 | #Output:'LOREM IPSUM' 361 | ``` 362 | 363 | -------------------------------------------------------------------------------- /Built-in-datatypes/Tuples/ReadMe.md: -------------------------------------------------------------------------------- 1 | **Author:** Anagha Sivadas T 2 | 3 | *** 4 | 5 | # Tuples 6 | 7 | Tuples are immutable sequences, typically used to store collections of heterogeneous data 8 | 9 | Tuples may be constructed in a number of ways: 10 | 11 | * Using a pair of parentheses to denote the empty tuple: `()` 12 | * Using a trailing comma for a singleton tuple: `a,` or `(a,)` 13 | * Separating items with commas: `a, b, c` or `(a, b, c)` 14 | * Using the `tuple()` built-in: `tuple()` or `tuple(iterable)` 15 | 16 | Examples 17 | 1. Input: 18 | ```python 19 | x=tuple('abc') 20 | print(x) 21 | ``` 22 | 23 | Output: `('a', 'b', 'c')` 24 | 25 | 2. Input: 26 | ```python 27 | y=tuple( [1, 2, 3] ) 28 | print(y) 29 | ``` 30 | 31 | 32 | Output: `(1, 2, 3)` 33 | 34 | 3. Input: 35 | ```python 36 | z=tuple() 37 | print(z) 38 | ``` 39 | Output: 40 | `()` 41 | 42 | 43 | **Note:** It is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. 44 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at varunhawk19@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Classes/Class_Variables.md: -------------------------------------------------------------------------------- 1 | **Author(s): Mohita Liza Bipin** 2 | 3 | **Editor(s): Pranav Shridhar** 4 | 5 | 6 | # Class Variables 7 | 8 | ### Declaration 9 | 10 | A class variable or static variable is shared by all objects of a class. 11 | 12 | Let's use the example of a bookshop whose items are objects of class 'Items'. 13 | 14 | ```python 15 | class Items: 16 | type = "book" 17 | def enter_info(self, name, genre): 18 | self.name = name 19 | self.genre = genre 20 | 21 | def print_info(self): 22 | print("Title : ", self.name, "\nGenre : ", self.genre, "\n\n") 23 | ``` 24 | 25 | The data member ```type``` is the same for each object as every item in the 26 | book store is the same (and is a book). 27 | 28 | Looking further into the topic let's create a few objects and call the methods 29 | for both and see what happens. 30 | 31 | ```python 32 | 33 | Book1= Items() 34 | Book2= Items() 35 | Book1.enter_info("The Hitchhiker's Guide to the Galaxy", "Comic Science Fiction") 36 | Book2.enter_info("The Stanger", "Philosophical Fiction") 37 | 38 | Book1.print_info() 39 | Book2.print_info() 40 | ``` 41 | 42 | The output will be : 43 | 44 | ``` 45 | Title: The Hitchhiker's Guide to the Galaxy 46 | Genre: Comic Science Fiction 47 | Type: book 48 | 49 | 50 | Title: The Stanger 51 | Genre: Philosophical Fiction 52 | Type: book 53 | ``` 54 | 55 | Notice how the type for both is the same? Well, that's how a class variable 56 | is. It's the same for all instances of the class. 57 | 58 | ### Altering a Class Variable 59 | 60 | The correct way to alter a class variable is by accessing the static variable 61 | through the **class name** and **not object name** 62 | 63 | ``` class_name.class_variable_name``` 64 | 65 | So let's try it out using 'Items' again : 66 | 67 | ```python 68 | 69 | Book1= Items() 70 | Book2= Items() 71 | 72 | Items.type="I am an awesome book!" #IMP 73 | 74 | Book1.enter_info("The Hitchhiker's Guide to the Galaxy", "Comic Science Fiction") 75 | Book2.enter_info("The Stanger", "Philosophical Fiction") 76 | 77 | Book1.print_info() 78 | Book2.print_info() 79 | ``` 80 | 81 | New output: 82 | 83 | ``` 84 | Title: The Hitchhiker's Guide to the Galaxy 85 | Genre: Comic Science Fiction 86 | Type: I am an awesome book! 87 | 88 | 89 | Title: The Stanger 90 | Genre: Philosophical Fiction 91 | Type: I am an awesome book! 92 | ``` 93 | 94 | See how the value of the data member changed for both objects and not just 95 | one? This shows that class variables are common to all objects of a class. 96 | 97 | *** 98 | ## [Alright...let's go ahead, Shall we?](https://github.com/vhawk19/Py_Primer/blob/master/Classes/Inheritance.md) 99 | -------------------------------------------------------------------------------- /Classes/Classes_and_Instances.md: -------------------------------------------------------------------------------- 1 | **Author(s): Mohita Liza Bipin, Pranav Shridhar** 2 | 3 | **Editor(s): S Sandeep Pillai** 4 | 5 | # Classes and Instances 6 | 7 | 8 | * A class defines a set of attributes for an object and an object is an instance of a class. 9 | 10 | * Attributes include data members and methods. 11 | 12 | * Methods are functions defined within a class and data members are variables which are also defined within a class. 13 | 14 | 15 | Yes, this seems a little complicated but it really isn't. Here's a simple analogy to help understand better : 16 | 17 | A class is very similar to a basic chocolate cake recipe. It has all the ingredients (data) and the instructions (methods) to bake a cake. The object here is the cake. 18 | 19 | Many objects can be made from a class and these objects can also be called instances. 20 | This process is called instantiation. 21 | 22 | Now that the definitions are out of the way we'll be taking a closer look at class and instances. 23 | 24 | ## Classes 25 | 26 | ### Defining a Class 27 | 28 | To define a class use the class keyword followed by the class name. 29 | 30 | ```python 31 | 32 | class Potato: 33 | ``` 34 | 35 | A local namespace containing the attributes is created when the class is defined where all attributes are defined. 36 | 37 | ### Docstrings 38 | 39 | Now looking at the class 'Potato' not a lot can be figured out about what exactly this class is for. 40 | That is where docstrings come in handy. 41 | 42 | Docstrings give anyone reading the code a heads up on what the class is used for. 43 | 44 | ```python 45 | class example: 46 | '''This is a docstring''' # -> Text enclosed by triple quotes. Explains the purpose of the class (when you hover over it in the text editor). 47 | ``` 48 | 49 | 50 | Now let's try applying this to our previous example, Potato. 51 | 52 | ```python 53 | class Potato: 54 | '''This class is a template of different types of potatoes''' 55 | ``` 56 | 57 | To access a docstring use the syntax: 58 | 59 | ``` classname.__doc__``` 60 | 61 | ```python 62 | print(Potato.__doc__) 63 | ``` 64 | 65 | So this will print the docstring of Potato and the output will be 66 | 67 | ```This class is a template of different types of potatoes``` 68 | 69 | 70 | ## Attributes 71 | 72 | 73 | As we saw earlier attributes are both data members and methods so now we're going to add some attributes to Potato 74 | 75 | ```python 76 | class Potato: 77 | '''This class is a template of different types of potatoes''' 78 | 79 | 80 | def info(self,kind): # self? what's that!? 81 | self.kind = kind 82 | ``` 83 | 84 | 'info' is an example of a method and 'kind' is a data member (attribute) describing the type of potato. 85 | 86 | *'self'* is a parameter as whenever a method is called the instance as a whole is passed automatically as the first parameter. 87 | 88 | 89 | ### Q: WAIT WAIT WAIT WAIT, WHAT IS THIS `SELF` KEYWORD??? 90 | 91 | If you're like me, having learned C++ and coming over to python, you might be utterly confused with the reason python uses the `self` keyword. In fact, **`self` is not a keyword, you can use any word you like!** 92 | 93 | 94 | So in short, the `self` object is used to denote an `instance` variable and its unique to that particular object of the class, not EVERY object of the class. 95 | 96 | Consider the code below: 97 | 98 | ```python3 99 | 100 | class A(): 101 | x=3 102 | 103 | class B(): 104 | def __init__(self): 105 | self.x=3 106 | 107 | ``` 108 | Here is an important distinction: 109 | 110 | A.x is a class variable, and will be **shared across all instances of A** unless specifically overridden within an instance. 111 | B.x is an instance variable, and **each instance of B has its own version of it.** 112 | 113 | 114 | The __init__ method is roughly what represents a constructor in Python (like in C/C++). When you call A() Python creates an object for you, and passes it ('self') as the first parameter to the __init__ method. 115 | 116 | ## Instances 117 | 118 | ### Creating an instance 119 | 120 | An instance can be defined as follows 121 | 122 | ```instance_name = class_name() ``` 123 | 124 | A new instance called 'instance_name' is created here. 125 | 126 | 127 | ### Accessing Attributes Through an instance 128 | 129 | The next step is to access an object's attributes which can be done using the dot operator '.' you might recognize it from earlier in the docstrings section. 130 | 131 | ```python 132 | instance_name.data 133 | instance_name.method() 134 | ``` 135 | 136 | Returning to Potato, we are now going to create an object tato which is a uni-tato (a cross of a unicorn and a potato). 137 | 138 | ```python 139 | class Potato: 140 | "This class is a template of different types of potatoes" 141 | 142 | 143 | def info(self,kind): 144 | self.kind = kind 145 | 146 | 147 | tato = Potato() 148 | tato.info('uni-tato') 149 | print('Type of potato is:',tato.kind) 150 | ``` 151 | 152 | Output: 153 | 154 | ``` 155 | Type of potato is: uni-tato 156 | ``` 157 | 158 | *** 159 | ## [Wanna know more??](https://github.com/vhawk19/Py_Primer/blob/master/Classes/Class_Variables.md) 160 | 161 | -------------------------------------------------------------------------------- /Classes/Inheritance.md: -------------------------------------------------------------------------------- 1 | **Author(s): Mohita Liza Bipin, Pranav Shridhar** 2 | 3 | # Inheritance 4 | 5 | A class can inherit attributes from another class called a super or parent class, 6 | the former is called the child class 7 | 8 | Compare this to fruit. Apples and strawberries are both fruits and have 9 | the same basic prerequisites for a typical fruit but each their own characteristics 10 | In this situation the parent class would be fruit and the child classes would be 11 | the apple and strawberry classes 12 | 13 | ### Syntax 14 | 15 | The syntax is fairly simple. 16 | 17 | ```python 18 | class class_name (super_class_name): 19 | #body 20 | ``` 21 | 22 | ### Time for an example 23 | 24 | So let's see an example based on the earlier one of fruits 25 | 26 | ```python 27 | class fruit(): 28 | 29 | def print_fruit(self): 30 | print("Contains seeds\n") 31 | 32 | 33 | class Apple(fruit): 34 | 35 | def print_apple(self): 36 | print("I'm an apple!") 37 | 38 | 39 | class Strawberry(fruit): 40 | def print_strawberry(self): 41 | print("I'm a strawberry") 42 | 43 | ``` 44 | 45 | As before Strawberry and Apple inherit from fruit which means all of their 46 | objects will have the attributes of the class fruit but why should you believe me? 47 | Let's test it out by creating objects and seeing what happens 48 | 49 | ```python 50 | a = Apple() 51 | s = Strawberry() 52 | 53 | a.print_apple() 54 | a.print_fruit() 55 | 56 | s.print_strawberry() 57 | s.print_fruit() 58 | ``` 59 | 60 | 61 | Output: 62 | 63 | ```python 64 | I'm an apple! 65 | Contains seeds 66 | 67 | I'm a strawberry 68 | Contains seeds 69 | ``` 70 | As you can see from the output both objects can access the attributes of the parent class 71 | 72 | *** 73 | ## [How about inheriting some theory on types of methods now??](https://github.com/vhawk19/Py_Primer/blob/master/Classes/typesOfMethods.md) 74 | -------------------------------------------------------------------------------- /Classes/exampleProgram.md: -------------------------------------------------------------------------------- 1 | ### Author: Pranav Shridhar 2 | # Example program illustrating classes. 3 | 4 | ```python 5 | class Car: 6 | def __init__(self, capacity, type, color, model): # Initiates instance/object 7 | 8 | # Attributes (Instance variables, in this case, since it is declared inside '__init__ method') 9 | self.capacity = capacity 10 | self.type = type 11 | self.color = color 12 | self.model = model 13 | 14 | 15 | # Methods 16 | def __repr__(self): # Reproduces object as output in a user friendly manner. Fallback to '__str__' 17 | return f"Car({self.capacity},{self.type},{self.color},{self.model})" 18 | 19 | def __str__(self): # Outputs a string as output for an object. 20 | return (f'{self.capacity},{self.type},{self.color},{self.model}') 21 | 22 | def oldOrNew(self): # Regular method -> requires instance(object) variable 'self' 23 | if 2018-self.model >= 2: 24 | return 'Old car' 25 | else: 26 | return 'New car' 27 | 28 | @classmethod # Decorator -> used for altering the behaviour of a function 29 | def someFunc(cls): # Class method -> requires class variable 'cls' 30 | pass 31 | 32 | @staticmethod 33 | def anotherFunc(): # Static method -> does not require either class or instance variable. Independent function 34 | pass 35 | 36 | 37 | class Chevrolet(Car): 38 | def __init__(self, capacity, type, color, model): 39 | super().__init__(capacity, type, color, model) # Inherits instance(object) variables from super class (Car) 40 | # Car.__init__(self, capacity, type, color, model) #same output -> useful for multilevel and other higher forms of inheritance where class name is specific. 41 | 42 | 43 | class Camaro(Chevrolet): # Multilevel Inheritance (Camaro inherits from Chevrolet which in turn inherits from Car) 44 | pass 45 | 46 | # Objects' creation 47 | car1 = Car(2, 'SUV', 'blue', 2010) 48 | car2 = Car(1.5, 'Sedan', 'black', 2017) 49 | chev1 = Chevrolet(3, 'MUV', 'red', 2012) 50 | camaro1 = Camaro(4, 'sports', 'yellow', 2015) 51 | 52 | # Accessing attributes and methods using 'dot' operator 53 | car1.oldOrNew() 54 | print(car1) 55 | chev1.oldOrNew() 56 | print(chev1) 57 | print(camaro1.oldOrNew()) 58 | help(camaro1) 59 | ``` 60 | -------------------------------------------------------------------------------- /Classes/typesOfMethods.md: -------------------------------------------------------------------------------- 1 | **Authors:** Pranav Shridhar and Mohita Bipin 2 | 3 | **Edits:** Ashley Thomas Roy 4 | 5 | *** 6 | 7 | # Decorators 8 | 9 | * A decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. 10 | * The function/method name is preceded by '@' symbol. 11 | * Eg. @classmethod and @staticmethod are the standard methods used in classes. 12 | 13 | Consider the following example* : 14 | ```python 15 | def make_pretty(func): 16 | def inner(): 17 | print("I got decorated") 18 | func() 19 | return inner 20 | 21 | def ordinary(): 22 | print("I am ordinary") 23 | ``` 24 | When you run the following codes in a shell 25 | 26 | ```python 27 | >>>ordinary() 28 | I am ordinary 29 | 30 | >>> # let's decorate this ordinary function 31 | >>> pretty = make_pretty(ordinary) 32 | >>> pretty() 33 | I got decorated 34 | I am ordinary 35 | ``` 36 | 37 | In the example shown above, make_pretty() is a decorator. In the assignment step, 38 | 39 | ```python 40 | pretty = make_pretty(ordinary) 41 | ``` 42 | 43 | The function ordinary() got decorated and the returned function was given the name pretty. 44 | 45 | We can see that the decorator function added some new functionality to the original function. This is similar to packing a gift. The decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. But now, it looks pretty (since it got decorated). 46 | 47 | Generally, we decorate a function and reassign it as, 48 | 49 | ``` 50 | ordinary = make_pretty(ordinary) 51 | ``` 52 | This is a common construct and for this reason, Python has a syntax to simplify this. 53 | 54 | We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be decorated. For example, 55 | 56 | ```python 57 | @make_pretty 58 | def ordinary(): 59 | print("I am ordinary") 60 | 61 | #is equivalent to 62 | 63 | def ordinary(): 64 | print("I am ordinary") 65 | ordinary = make_pretty(ordinary) 66 | ``` 67 | 68 | 69 | # Regular Methods, Class Methods, and Static Methods 70 | 71 | ## Regular Methods 72 | * They are plain functions written inside a class. They require an instance variable. 73 | * The word 'self' is generally used in the naming of the first argument which refers to the current instance. 74 | * The statements written inside this affects a single instance/object presently in use. 75 | * It requires no additional syntax. 76 | 77 | Example : 78 | ```python 79 | def Addition(self, a, b): # 'a' and 'b' are instance variables 80 | sum = a + b 81 | return sum 82 | ``` 83 | 84 | The above function returns the sum of two variables held inside one instance. 85 | 86 | ## Class Methods 87 | 88 | * They are methods/functions which require a class variable. 89 | * The word 'cls' is generally used in the naming of the argument which refers to the current class. 90 | * The statements written inside this affects the entire class instances/objects. 91 | * The decorator keyword '@classmethod' is used before the actual function. 92 | 93 | Example : 94 | ```python 95 | class Employee: 96 | 97 | raise_amount = 1 # class variable 98 | 99 | ... 100 | ... 101 | 102 | @classmethod 103 | def raise_salary(cls): 104 | raise_amount = 1.5 105 | return None 106 | ``` 107 | 108 | The above function upon calling changes the value of 'raise_amount' to 1.5 for all the instances. 109 | 110 | ## Static Methods 111 | 112 | * They are methods/functions which do require neither class variable nor instance variable. 113 | * The decorator keyword '@staticmethod' is used before the actual function. 114 | * Static methods, much like class methods, are methods that are bound to a class rather than its object. 115 | * They do not require a class instance creation. So, are not dependent on the state of the object. 116 | 117 | Example : 118 | ```python 119 | class Person: 120 | def __init__(self, name, age): 121 | self.name = name 122 | self.age = age 123 | 124 | @staticmethod 125 | def isAdult(age): 126 | return age > 18 127 | ``` 128 | 129 | 130 | ### Difference b/w classmethod and staticmethod 131 | 132 | * Static method knows nothing about the class and just deals with the parameters. 133 | * The class method works with the class since its parameter is always the class itself. 134 | 135 | 136 | 137 | --- 138 | #### References 139 | 140 | * Example* for decorators taken from https://www.programiz.com/python-programming/decorator 141 | 142 | *** 143 | ## [Searching for an example??](https://github.com/vhawk19/Py_Primer/blob/master/Classes/exampleProgram.md) 144 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines:blue_book: 2 | 3 | So you have gone through Py_Primer and now you want to start contributing. 4 | That's great! Python is always changing and keeping the primer relevent is 5 | an important task. We are always looking for people to help keep it up to date 6 | 7 | 8 | ### Wait! Why should I even bother reading this?:smirk: 9 | 10 | We want to keep it easy to contribute and maintaing structure is the best 11 | way to prevent the primer from falling into anarchy. Ok I'm being a bit melodramatic 12 | here. We just want the process of contributing to flow smoothly with out any hitches. 13 | 14 | ### What kind of contributions are you even looking for?:smiley: 15 | 16 | Almost any kind of contribution is welcome as long as the guidelines are 17 | followed. No contribution is too small. Go ahead and correct grammar or spelling 18 | mistakes. Add a new topic or even a new feature if you're up to it! 19 | 20 | ## The Ground Rules:straight_ruler: 21 | #### (Don't panic! There are only two) 22 | 23 | 24 | * If you want to update present topics or example code; go ahead and 25 | pull a request after making your own fork and adding your changes. 26 | 27 | 28 | * Say you want to do something a little bigger such as adding a new file or feature; 29 | in that case open an issue and discuss how to go about it there before making any changes. 30 | 31 | 32 | ### That's it (:sparkles:yay~) 33 | 34 | Seriously that's it.Now you can start contributing whenever you like! 35 | 36 | -PyPrimer Team 37 | 38 | 39 | *** 40 | (V 0.42) 41 | -------------------------------------------------------------------------------- /Functions/1_Introduction_to_Functions.md: -------------------------------------------------------------------------------- 1 | **Author:** S Sandeep Pillai. 2 | 3 | **Edits:** Ashley TR, Pranav Shridhar 4 | 5 | *** 6 | 7 | # Functions 8 | 9 | **A function (or method) is defined as a named encapsulation of a specific set of instructions in a program.** 10 | 11 | In normal English, it can be considered as a package/collection of lines of code that will be executed each time you 'call' it later on in your program. So this splits the program into "modules" or chunks that each person can work on separately. 12 | 13 | Now before we get into the boring theory, let us delve into how we can use functions in Python. 14 | 15 | ## Syntax 16 | 17 | There are two kinds of functions within python: 18 | 1) Built-In Functions 19 | 2) User Defined Functions 20 | 21 | Implicit Functions are predefined functions within Python, or a module linked through Python. We shall focus on Explicit Functions 22 | for now. 23 | 24 | ### Stop it with the Theory! 25 | 26 | Okay, fine, so a function needs to be defined beforehand for it to be used later in the program. To define a function, we need 27 | to use the following keywords: 28 | 29 | ```python 30 | def function-name ( Argument-1, Argument-2, ... Argument-N ): #Make sure you don't forget the colons in the end! (' : ') 31 | 32 | Line 1 33 | Line 2: 34 | Line 2.1 35 | Line 2.2 36 | Line 2.3: 37 | Line 2.3.1 38 | Line 2.3.2 39 | Line 3 40 | Line 4 41 | 42 | #End of "function-name". 43 | ``` 44 | Here, we use the keyword *`def`* to invoke the function definition clause so that the interpreter will know the following line 45 | contains the definition of a function. To use this function later, simply follow the syntax: 46 | 47 | ```python 48 | 49 | function-name( Arg1, Arg2, ArgN ): #This will execute Lines 1 to 4 once. 50 | 51 | ``` 52 | 53 | Now let us look at an example where functions can prove very useful in your program you will be writing. 54 | 55 | Suppose we are developing a college-assistant application, with a wide range of tools such as a 'timetable manager', 'announcements viewer', 'test date reminders', and the very popular 'Class Bunker Calculator', it would be convenient to enclose each functionality within its own functions. 56 | 57 | ## Example Program: 58 | 59 | But for now, let us diverge from that and look at how we can design a simple arithmetic calculator: 60 | 61 | ```python 62 | 63 | def add(num1, num2): # This function will take in 2 variable arguments. 64 | sum = num1 + num2 # These arguments are added together and stored in the variable 'sum'. 65 | print(sum) # The variable sum is then printed onto the console. 66 | 67 | def subtract(num1, num2): 68 | print( num1 - num2 ) # Another method would be to simply print out the compound statement as shown, avoiding the 69 | # the usage of a variable such as 'sum', helping reduce memory usage. 70 | 71 | def multiplication(num1, num2): 72 | multip = num1 * num2 73 | print(multip) 74 | 75 | def division(num1, num2): 76 | div = num1 / num2 77 | return(div) # We can instead return the value, if we wish to use this value for other purposes in the program. 78 | 79 | def odd_even_checker(num1): 80 | if num1 % 2 == 0: # We can implement an if clause in a function, as shown here. 81 | print("EVEN") 82 | else: 83 | print("ODD") 84 | 85 | 86 | 87 | ``` 88 | We can now call any of the functions defined above as many times as we want later in the program. Let us assume later in the code, we need to multiply 42 and 25. We can simply "CALL" the `multiplication` function in the lines below instead of writing the entire sequence of code again. 89 | ```python3 90 | 91 | multiplication( 42, 25 ) # Here, 42 is assigned to num1 and 25 is assigned to num2. 92 | 93 | ``` 94 | 95 | This will give us the output : 96 | 97 | 98 | ``` 99 | 1050 100 | ``` 101 | 102 | **NOTE: Useful Built-In functions are discussed in the other modules of this 'textbook' ** 103 | 104 | ## Advantages of using a function: 105 | 106 | * It allows for a significantly shorter length of the program code. 107 | * You can reuse the code repeatedly (by calling the function) instead of rewriting the same set of instructions again. 108 | * Significantly improves code debugging - it will allow you to pinpoint an error to a specific code block. 109 | * If a certain function breaks during development, you can still run the rest of the program without issues (by commenting out that particular function). 110 | * Allows division of labour: each member can work on a separate function without conflicting code. 111 | 112 | *** 113 | ## [Interesting? You might also be interested in the compound and built-in functions](https://github.com/vhawk19/Py_Primer/blob/master/Functions/2_BuiltIn_%26_Composition_Functions.md) 114 | -------------------------------------------------------------------------------- /Functions/2_BuiltIn_&_Composition_Functions.md: -------------------------------------------------------------------------------- 1 | **Author:** S Sandeep Pillai 2 | 3 | **Edit(s):** Pranav Shridhar 4 | 5 | *** 6 | 7 | Now let us look at some of the inbuilt functions (that you need to by heart lol). 8 | 9 | # Inbuilt Functions 10 | 11 | Modules are basically header files in python, which you can `link` in your program to get access to a vast collection of 12 | functions and features. 13 | 14 | To 'import' a module into your program, you can use the following syntax: 15 | 16 | ```python 17 | 18 | import modulename 19 | 20 | ``` 21 | That's it! Now you can use the vast amount of functions and features that the module provides in your program, without having 22 | to write new functions yourself! 23 | 24 | ## Math Module 25 | 26 | ```python 27 | import math 28 | ``` 29 | 30 | The math module contains various functions that can be useful for mathematical functionality in your program. A few useful 31 | functions include: 32 | 33 | ### math.pow( a , b ) 34 | 35 | `This function will output the number "a raised to the power b"` 36 | 37 | ```python 38 | math.pow(2,3) # Input 39 | >>> 8 # Output 40 | ``` 41 | ### math.sqrt(a) 42 | 43 | `This function will output the square root of a` 44 | 45 | ```python 46 | math.sqrt(49) # Input 47 | >>> 7 # Output 48 | ``` 49 | 50 | ### math.sin(a) 51 | 52 | `This function will return the trignometric sine ratio of a *radians* ` 53 | 54 | ```python 55 | math.sin( math.pi / 2 ) # Input: math.pi can be used to get an accurate value of π 56 | >>> 8 # Output 57 | ``` 58 | ### math.log10(a) 59 | 60 | `This function will return the log a to the base 10 value.` 61 | 62 | ```python 63 | math.log10(1000) # Input 64 | >>> 3 # Output 65 | ``` 66 | 67 | --- 68 | By now, if you are tired of typing out 'math' repeatedly, you can opt for a shorthand style as follows : 69 | 70 | ```python 71 | import math as m 72 | m.sin(m.pi/2) # Input 73 | >>> 8 # Output 74 | ``` 75 | --- 76 | 77 | Below I shall list a few more important functions that can be useful: 78 | 79 | ```python 80 | 81 | abs(x-y) 82 | # Basically acts as a modulus function, giving the distance between x and y. Note that abs isn't part of the math module. 83 | 84 | math.ceil(x) 85 | # Returns the smallest integer greater than x, i.e 1.2 will give 2 as the output. Think Ceiling - Above. 86 | 87 | math.floor(x) 88 | # Returns the smallest integer lesser than x, i.e 1.2 will give 1 as the output. Think Floor - Below. 89 | 90 | math.exp(x) 91 | # Returns e^x 92 | 93 | ``` 94 | 95 | # Composition of functions 96 | 97 | Functions have a very useful feature where we can give a specific function as an argument for another function. This is 98 | particularly useful in the following example: 99 | 100 | ```python 101 | 102 | math.pow( math.sin(π/6) , 2) # Input: (sin30)^2 103 | >>>0.25 # Output 104 | ``` 105 | 106 | *** 107 | 108 | 109 | ## [Wanna know about lambda functions and its fancy features??](https://github.com/vhawk19/Py_Primer/blob/master/Functions/3_Lambda_Expressions.md) 110 | -------------------------------------------------------------------------------- /Functions/3_Lambda_Expressions.md: -------------------------------------------------------------------------------- 1 | 2 | _Author : Ashley Thomas Roy_ 3 | *** 4 | # Lambda Expressions :sweat_smile: 5 | 6 | **_Lambda expressions_** allow us to create an anonymous function. We can quickly make functions for a particular purpose without having to properly define a function using `def`. 7 | 8 | **_Lambda expressions_** are a single statement. They work exactly like functions created using `def`. The only key difference is that their result is typed in as an expression and doesn't need to be explicitly returned. 9 | 10 | *** 11 | 12 | ### Example: 13 | 14 | _Imagine we have a function `square()` which returns the square of an argument passed to it,_ 15 | ```python 16 | def square(x): 17 | return x*x 18 | square(5) 19 | 20 | #Output: 25 21 | ``` 22 | _We can instead write this as a lambda expression as,_ :heavy_check_mark: 23 | ```python 24 | #We do not usually assign a lambda expression to a variable. This is just for demonstration purposes. 25 | square = lambda x: x*x 26 | square(5) 27 | 28 | #Output: 25 29 | ####Seeeeee! Much easier.....Still confused? More examples coming up! 30 | ``` 31 | 32 | *** 33 | 34 | **_Lambda expressions_** are usually used in combination with other functions like map and filter. 35 | 36 | map() 37 | --- 38 | `map()` function allows us to "map" a function to an iterable object, i.e., the function is called and executed for each element of the iterable object. However, in order to get results from `map()` we need to either iterate through the map or simply cast it to a list. 39 | 40 | ### Example: 41 | 42 | ```python 43 | def square(x): 44 | return x**2 45 | m=[1,2,3,4,5] #list 46 | l=map(square,m) 47 | print(l) 48 | 49 | #Output: [1,4,9,16,25] 50 | 51 | #OR (No need to learn both....CHILL!!!) 52 | 53 | def square(x): 54 | return x**2 55 | m=[1,2,3,4,5] #list 56 | print(list(map(square,m))) 57 | 58 | #Output: [1,4,9,16,25] 59 | ``` 60 | _This can be written using lambda expressions as,_ :heavy_check_mark: 61 | 62 | ```python 63 | a=[1,2,3,4,5] 64 | l=map(lambda x: x**2,a) 65 | print(l) 66 | 67 | #Output: [1,4,9,16,25] 68 | ``` 69 | 70 | filter() 71 | --- 72 | It receives a function and an iterable object as arguments. The function should return a True or False value. You will get back only those elements as results which when passed through the function return True. 73 | 74 | ### Example: 75 | 76 | ```python 77 | m=[1,2,3,4,5] 78 | def check_even(x): 79 | return x%2==0 80 | even=filter(check_even,m) 81 | print(even) 82 | 83 | #Output: [2,4] 84 | 85 | #OR 86 | 87 | m=[1,2,3,4,5] 88 | def check_even(x): 89 | return x%2==0 90 | print(list(filter(check_even,x))) 91 | 92 | #Output: [2,4] 93 | ``` 94 | _This can be written using lambda expressions as,_ :heavy_check_mark: 95 | ```python 96 | m=[1,2,3,4,5] 97 | print(list(filter(lambda x: x%2==0,m))) 98 | 99 | #Output: [2,4] 100 | ``` 101 | 102 | *** 103 | 104 | ## More Examples: 105 | 106 | _1.Lambda expression to grab the first character of a string_ 107 | ```python 108 | lambda s: s[0] 109 | ``` 110 | 111 | _2.Lambda expression to reverse a string_ 112 | ```python 113 | lambda s: s[::-1] 114 | ``` 115 | 116 | **:eight_spoked_asterisk: :_LAMBDA EXPRESSIONS_ CAN ALSO TAKE MULTIPLE ARGUMENTS :scream_cat:** 117 | 118 | _3.Lambda expression to add two numbers_ 119 | ```python 120 | lambda x,y: x+y 121 | ``` 122 | 123 | *** 124 | *** 125 | That was EZ :sunglasses: 126 | 127 | 128 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /Learn to handle your file/Introduction.md: -------------------------------------------------------------------------------- 1 | **Authors:** Annu Jolie 2 | 3 | **Edits:** Pranav Shridhar 4 | 5 | *** 6 | 7 | 8 | # Introduction 9 | __________________________________________________________ 10 | 11 | Suppose you are working on a very important project and you are entering some valuable data into your program. While a program is running, its data is stored in random access memory (RAM). RAM is fast and inexpensive, but it is also volatile, which means that when the program ends, or the computer shuts down, data in RAM disappears. Hence, if the power goes off all your hard work and valuable data goes into vain. To make data available the next time the computer is turned on and the program is started, it has to be written to a non-volatile storage medium, such a hard drive, usb drive, or CD-RW. Data on non-volatile storage media is stored as files. 12 | 13 | 14 | Python files are the same as other files on your computer: documents, pictures, music, games . . . indeed, everything on your computer is stored as files. 15 | 16 | 17 | 18 | 19 | 20 | 21 | Working with files is a lot like working with a notebook. 22 | 23 | To use a notebook : 24 | * It has to be opened. 25 | * When done, it has to be closed. 26 | * While the notebook is open, it can either be read from or written to. 27 | * In either case, the notebook holder knows where they are. They can read the whole notebook in its natural order or they can skip around. 28 | 29 | Similarly in python, a file operation takes place in the following order. 30 | 1. Open a file 31 | 2. Read or write (perform operation) 32 | 3. Close the file 33 | 34 | It's as simple as that. So lets get our hands dirty, and start writing out first file program[Click here ](https://github.com/annu12340/Py_Primer/blob/master/Learn%20to%20handle%20your%20file/writing%20to%20a%20file.md) 35 | 36 | -------------------------------------------------------------------------------- /Learn to handle your file/Reading from a file.md: -------------------------------------------------------------------------------- 1 | **Authors:** Annu Jolie 2 | 3 | **Edits:** Pranav Shridhar, Diya Maria Deepak 4 | 5 | *** 6 | 7 | 8 | ## Reading the entire file in a go 9 | In the previous page you have learned how to write into a file. Now let us understand how to read from a file. 10 | 11 | 12 | 13 | Previously we have created a new file, called "test.txt" having the following contents in it : 14 | ``` 15 | This is my first python program. 16 | I am really excited about it!! 17 | ``` 18 | To read a file in Python, we must open the file in read mode.Then we use read() method for reading the content of the file : 19 | 20 | ```python 21 | f = open("test.txt", "r") 22 | print(f.read()) 23 | ``` 24 | The above program prints out the content of test.txt file. Once the end of file is reached, we get empty string on further reading. 25 | 26 | _____________________________________________________ 27 | 28 | ## Reading only Parts of the File 29 | By default the read() method returns the whole text, but you can also specify how many character you want to return using read(size) method. Here 'size' is the number of bytes to be read from the opened file. 30 | 31 | **_Example_** 32 | ```python 33 | new_file = open("test.txt", "r") 34 | print(new_file.read(13)) 35 | new_file.close() 36 | ``` 37 | The output of the code will be :- 38 | ```python 39 | This is my fi 40 | ``` 41 | _____________________________________________________ 42 | 43 | 44 | ### Read the file line by line 45 | You can read the contents of a file, line by line by using the readline() method.If have a very long file, readline() method is more efficient and convenient 46 | 47 | **_Example I_** - Read one line of the file : 48 | 49 | ```python 50 | f = open("test.txt", "r") 51 | print(f.readline()) 52 | 53 | ``` 54 | The output of the code will be :- 55 | ```python 56 | This is my first python program. 57 | ``` 58 | 59 | **_Example II_** - By calling readline() two times, you can read the two first lines : 60 | 61 | ```python 62 | f = open("test.txt", "r") 63 | print(f.readline()) 64 | print(f.readline()) 65 | 66 | ``` 67 | The output of the code will be :- 68 | ```python 69 | This is my first python program. 70 | I am really excited about it!! 71 | ``` 72 | 73 | -------------------------------------------------------------------------------- /Learn to handle your file/writing to a file.md: -------------------------------------------------------------------------------- 1 | **Authors:** Annu Jolie 2 | 3 | **Edits:** Pranav Shridhar, Diya Maria Deepak 4 | 5 | *** 6 | 7 | 8 | ## A simple file program 9 | 10 | Now let us try to write a simple python program to add text into an empty file. 11 | 12 | ```python 13 | new_file = open("test.txt", "w") 14 | new_file.write("This is my first python program \n I am really excited about it!!) 15 | new_file.close() 16 | ``` 17 | 18 | Let us try to break it down and understand each line of code in the above program. 19 | ### Line 1- 20 | ```diff 21 | + Open() function 22 | 23 | ``` 24 | 25 | On the first line, we have the open function.We declared a variable *new_line* to open a file named text.txt The open() function takes two parameters:- filename and mode. 26 | 27 | 1. **Filename**: This is a string tells Python where to find the file. If you’re using Windows, you saved test.txt to the local disk on the C: drive, so you specify the location of your file as c:\\test.txt 28 | 29 | 2. **Mode**: Here we used "w" letter in our argument, which indicates write mode.This arguement tells python whether we are reading from a file or writing into it. Other than "w", we have different other modes for opening a file 30 | 31 | *Different methods (modes) for opening a file :* 32 | 33 | * "r" - Read : Default value. Opens a file for reading, error if the file does not exist. 34 | * "a" - Append : Opens a file for appending, creates the file if it does not exist. 35 | * "w" - Write : Opens a file for writing, creates the file if it does not exist. 36 | 37 | In addition you can specify if the file should be handled as binary or text mode 38 | * "t" - Text : Default value. Text mode 39 | * "b" - Binary : Binary mode (e.g. images) 40 | _____________________ 41 | ### Line 2- 42 | ```diff 43 | + write() function 44 | 45 | ``` 46 | 47 | Now we have successfully opened the file in write mode.In the second line, we have the write function. Inside the write function, we specify the content we want write into our file. 48 | 49 | **Append() function**:- 50 | 51 | If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful!! 52 | Inorder to avoid this, we have the append function. The append function is used to append to the file instead of overwriting it. 53 | To append to an existing file, simply open the file in append mode ("a"): 54 | ______________________________ 55 | ### Line 3- 56 | ```diff 57 | + close() function 58 | 59 | ``` 60 | 61 | After writing into the file finally, we need to tell Python when we’re finished, by using the close function.It free up any system 62 | resources taken up by the open file.Python automatically closes a file when the reference object of a file is reassigned to another file. However it is a good practice to use the close() method to close a file. 63 | 64 | ______________________________ 65 | 66 | 67 | We have successfully created a new file and entered some contents to it. Let us see one more example :- 68 | 69 | #### *Example II* 70 | 71 | 72 | Here we open a file called *new.txt*. We have a *for loop* that runs over a range of 5 numbers.We use the write function to enter data into the file. 73 | ```python 74 | f= open("new.txt","a") 75 | for i in range(5): 76 | f.write("This is line "+str((i+1))+"\n") 77 | f.close() 78 | 79 | ``` 80 | The result after code execution is as follows :- 81 | ```python 82 | This is line 1 83 | This is line 2 84 | This is line 3 85 | This is line 4 86 | This is line 5 87 | ``` 88 | 89 | 90 | Now let us try to read the contents from a file. 91 | [ Click here ](https://github.com/annu12340/Py_Primer/blob/master/Learn%20to%20handle%20your%20file/Reading%20from%20a%20file.md) 92 | 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Py_Primer:snake: 2 | 3 | Hey, there aspiring coder! :smiley: 4 | Sick of going through your boring textbook? 5 | Choose and learn freely whatever you want from this categorized repo! 6 | We have explained concepts in an intuitive and fun manner. 7 | We also have In-built Methods documentation with examples documented in a formal but beginner-friendly manner! 8 |
9 | 10 | ### [Want to contribute to this Repo? Click Me!!](https://github.com/vhawk19/Py_Primer/blob/master/Contributing.md) 11 | *** 12 | 13 | ## Contents 14 | + ### [str("strings are easy,but there are so many methods!!")](https://github.com/vhawk19/Py_Primer/blob/master/Built-in-datatypes/Strings/ReadMe.md) 15 | + ### [['L','i','s','t','s']](https://github.com/vhawk19/Py_Primer/blob/master/Built-in-datatypes/Lists/ReadMe.md) 16 | + ### [('T','u','p','l','e','s')](https://github.com/vhawk19/Py_Primer/blob/master/Built-in-datatypes/Tuples/ReadMe.md) 17 | + ### [Dictionary={'key':'value'}](https://github.com/vhawk19/Py_Primer/blob/master/Built-in-datatypes/Dictionary/ReadMe.md) 18 | + ### [FUNCtions(intro,builtin,complex[,lambda])](https://github.com/vhawk19/Py_Primer/blob/master/Functions/1_Introduction_to_Functions.md) 19 | + ### [class learnClasses:](https://github.com/vhawk19/Py_Primer/blob/master/Classes/Classes_and_Instances.md) 20 | + ### [Learn to Handle your File!](https://github.com/vhawk19/Py_Primer/blob/master/Learn%20to%20handle%20your%20file/Introduction.md) 21 | 22 | *** 23 | 24 | ### GiVe iT a SHot! :joy: 25 | *** 26 | 27 | ### [Help us out by leaving a review! Click me please! (DoNT be ToO HaRSh :cry:)](https://goo.gl/forms/pmOLbLB4PXnbxBXU2) 28 | 29 | 30 | #### [You can make it better!](https://github.com/vhawk19/Py_Primer/blob/master/Contributing.md) 31 | 32 | *** 33 | 34 | # Developed by: 35 | + #### [vhawk19](https://github.com/vhawk19) (Varun) 36 | + #### [Corruption13](https://github.com/Corruption13) (Sandeep) 37 | + #### [annu12340](https://github.com/annu12340) (Annu) 38 | + #### [ATR-OC](https://github.com/ATR-OC) (Ashley) 39 | + #### [pranavmodx](https://github.com/pranavmodx) (Pranav) 40 | + #### [Diya8](https://github.com/Diya8) (Diya) 41 | + #### [VoxEtMohita](https://github.com/VoxEtMohita) (Mohita) 42 | + #### [angie1015](https://github.com/angie1015) (Anagha) 43 | + #### [emmanuelantony2000](https://github.com/emmanuelantony2000) (Emmanuel) 44 | 45 | 46 | *** 47 | 48 | (V 1.42) 49 | --------------------------------------------------------------------------------