@@ -145,6 +145,39 @@ Available in Python 3.6+. Works similar to the above, but is more powerful as ar
145
145
' Five plus ten is 15 and not 30.'
146
146
```
147
147
148
+ ## Function
149
+ Function is a block of code which runs when it is called.
150
+ Functions are declared using the ` def ` keyword. Function name must be a valid identifier.
151
+ Function arguments can be literal values, variables (valid identifiers), and expressions.
152
+ ``` python
153
+ def sum (a , b ) :
154
+ return a + b
155
+
156
+ def subtract (a , b ) :
157
+ return a - b
158
+
159
+ def getPerson (name , age ) :
160
+ person = { " name" : name, " age" : age }
161
+ return person
162
+ ```
163
+
164
+ #### Function Call
165
+ Functions can be called by passing the arguments according to the declaration.
166
+ ``` python
167
+ a = 20
168
+ b = 50
169
+ c = sum (a, b)
170
+ d = sum (b, 50 )
171
+ e = subtract(b, a)
172
+ p = getPerson(" Joe" , 25 )
173
+
174
+ # OUTPUT:
175
+ print ( " Sum - {} plus {} : {} " . format ( a, b, c ) ) # Sum - 20 plus 50: 70
176
+ print ( " Sum - {} plus 50: {} " . format ( b, d ) ) # Sum - 50 plus 50: 100
177
+ print ( " Subtraction - {} minus {} : {} " . format ( b, a, e ) ) # Subtraction - 50 minus 20: 30
178
+ print ( " Person - {} " . format ( p ) ) # Person - {'name': 'Joe', 'age': 75}
179
+ ```
180
+
148
181
## Data Structures
149
182
150
183
### Lists
@@ -186,8 +219,47 @@ len(<dict>) # Find the length of the diction
186
219
```
187
220
A dictionary can also contain many dictionaries, this is called nested dictionaries.
188
221
189
- ## Third party libraries
222
+ ### Tuple
223
+ A tuple is a collection which is ordered, indexed and unchangeable. In Python tuples are written with round brackets.
224
+ ``` python
225
+ this_tuple = (' books' , ' pen' , ' paper' ) # Defined a tuple
190
226
227
+ # Accessing Tuple Items
228
+ print (this_tuple[2 ]) # paper
229
+ ```
230
+
231
+ #### Changing Tuple Values
232
+ Tuples are immutable, which means they cant to changed once they are created.
233
+ If a value inside tuple needs to be changed, the tuple must be converted to a list.
234
+ Newly created list can be converted back to tuple after updating changes.
235
+ ``` python
236
+ desk_tuple = (" pen stand" , " plant" , " marker" )
237
+ desk_list = list (desk_tuple)
238
+ desk_list[2 ] = " highlighter"
239
+ desk_tuple = tuple (desk_list)
240
+
241
+ print (desk_tuple[2 ]) # highlighter
242
+ ```
243
+
244
+ #### Creating tuple with one item
245
+ To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
246
+ ``` python
247
+ this_tuple = (" Python" ,)
248
+ print (type (this_tuple)) # tuple
249
+
250
+ # NOT a tuple
251
+ this_tuple = (" Python" )
252
+ print (type (this_tuple)) # str
253
+ ```
254
+
255
+ #### Deleting a tuple
256
+ Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
257
+ ``` python
258
+ this_tuple = (' books' , ' pen' , ' paper' )
259
+ del this_tuple
260
+ print (this_tuple) # ERROR: this_tuple is not defined
261
+ # # Third party libraries
262
+ ```
191
263
### Pandas
192
264
``` shell
193
265
$ sudo pip3 install pandas # Installing pandas module in Ubuntu
@@ -212,45 +284,99 @@ nltk.download('punkt')
212
284
nltk.download(' averaged_perceptron_tagger' )
213
285
```
214
286
287
+ ## Errors and Exceptions
288
+ Program stops working on error Python raises exceptions when it encounter error.
289
+ To avoid this, ` try-catch ` blocks are used.
290
+
291
+ # Exceptions
292
+ No syntax errors found, program starts execution.
293
+ Errors detected during execution are called exceptions.
294
+ Use try: except: finally: to catch and handle the exceptions.
295
+ Use try: except: finally: to avoid program termination on exceptions.
296
+ Use try: except: else: instead of try: except: finally: for alternate flows.
297
+ Multiple except can be use to catch the exceptions.
298
+
299
+ ``` python
300
+ a = 10 * (1 / 0 )
301
+
302
+ # Throws division by zero exception and terminate the program
303
+ # Traceback (most recent call last):
304
+ File " " , line 1 , in
305
+ a = 10 * (1 / 0 )
306
+ # ZeroDivisionError: division by zero
307
+
308
+ # Updated Program - Valid - Try: Except: Finally
309
+ b = 10
310
+ try :
311
+ a = 10 * (1 / b)
312
+ print ( " a = {} " .format( a ) )
313
+ except :
314
+ print ( " Caught divide by zero - while getting a" )
315
+ print ( " Execute on error - b must be non-zero value" )
316
+ finally :
317
+ print ( " Execute Always - normal and exceptional flow" )
318
+
319
+ # OUTPUT
320
+ a = 1.0
321
+ Execute Always - normal and exceptional flow
322
+
323
+ # # Updated Program - Error - Try: Except: Finally
324
+ b = 0
325
+ try :
326
+ a = 10 * (1 / b)
327
+ print ( " a = {} " .format( a ) )
328
+ except :
329
+ print ( " Caught divide by zero - while getting a" )
330
+ print ( " Execute on error - b must be non-zero value" )
331
+ else :
332
+ print ( " Alternate to exceptional flow" )
333
+
334
+ # Output
335
+ Caught divide by zero - while getting a
336
+ Execute on error - b must be non- zero value
337
+ Execute Always - normal and exceptional flow
338
+ ```
339
+
215
340
## Python Snippets
216
341
217
342
### Anagrams
218
343
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
219
- ```
344
+ ``` python
220
345
from collections import Counter
221
346
def anagram (first , second ):
222
347
return Counter(first) == Counter(second)
223
348
anagram(" abcd3" , " 3acdb" ) # True
224
349
```
225
350
### Memory
226
351
This snippet can be used to check the memory usage of an object.
227
- ```
352
+ ``` python
228
353
import sys
229
354
230
355
variable = 30
231
356
print (sys.getsizeof(variable)) # 24
232
357
```
233
358
### Print a string N times
234
359
This snippet can be used to print a string n times without having to use loops to do it.
235
- ```
360
+ ``` python
236
361
n = 2
237
362
s = " Programming"
238
363
print (s * n) # ProgrammingProgramming
239
364
```
240
365
### Chunk
241
366
This method chunks a list into smaller lists of a specified size.
242
- ```
367
+ ``` python
243
368
def chunk (list , size ):
244
369
return [list[i:i+ size] for i in range (0 ,len (list ), size)]
245
370
```
246
371
### Get vowels
247
372
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
248
- ```
373
+ ``` python
249
374
def get_vowels (string ):
250
375
return [each for each in string if each in ' aeiou' ]
251
376
get_vowels(' foobar' ) # ['o', 'o', 'a']
252
377
get_vowels(' gym' ) # []
253
378
```
379
+
254
380
### Length of Last Word in a string
255
381
This method gets the length of last word in a given string.
256
382
```
@@ -288,4 +414,17 @@ def countNegatives(self, grid: List[List[int]]) -> int:
288
414
if n < 0:
289
415
count += 1
290
416
return count
291
- ```
417
+ ```
418
+
419
+ ### Write to file
420
+ This method takes in the `` name of file `` and `` content `` then write the content into the file. If the file doesn't exist then it creates the file.
421
+ ``` python
422
+ def write_to_file (filename , content ):
423
+ try :
424
+ with open (filename, " w+" ) as f:
425
+ f.write(content)
426
+ print (" Written to file successfully." )
427
+ except Exception as e:
428
+ print (" Failed to write to file with error: " )
429
+ print (e)
430
+ ```
0 commit comments