Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 273eccb

Browse files
Merge branch 'master' into nehal-gupta_4
2 parents b16e517 + e079ca1 commit 273eccb

File tree

1 file changed

+146
-7
lines changed

1 file changed

+146
-7
lines changed

‎README.md

Lines changed: 146 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,39 @@ Available in Python 3.6+. Works similar to the above, but is more powerful as ar
145145
'Five plus ten is 15 and not 30.'
146146
```
147147

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+
148181
## Data Structures
149182

150183
### Lists
@@ -186,8 +219,47 @@ len(<dict>) # Find the length of the diction
186219
```
187220
A dictionary can also contain many dictionaries, this is called nested dictionaries.
188221

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
190226

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+
```
191263
### Pandas
192264
```shell
193265
$ sudo pip3 install pandas # Installing pandas module in Ubuntu
@@ -212,45 +284,99 @@ nltk.download('punkt')
212284
nltk.download('averaged_perceptron_tagger')
213285
```
214286

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+
215340
## Python Snippets
216341

217342
### Anagrams
218343
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
220345
from collections import Counter
221346
def anagram(first, second):
222347
return Counter(first) == Counter(second)
223348
anagram("abcd3", "3acdb") # True
224349
```
225350
### Memory
226351
This snippet can be used to check the memory usage of an object.
227-
```
352+
```python
228353
import sys
229354

230355
variable = 30
231356
print(sys.getsizeof(variable)) # 24
232357
```
233358
### Print a string N times
234359
This snippet can be used to print a string n times without having to use loops to do it.
235-
```
360+
```python
236361
n = 2
237362
s ="Programming"
238363
print(s * n) # ProgrammingProgramming
239364
```
240365
### Chunk
241366
This method chunks a list into smaller lists of a specified size.
242-
```
367+
```python
243368
def chunk(list, size):
244369
return [list[i:i+size] for i in range(0,len(list), size)]
245370
```
246371
### Get vowels
247372
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
248-
```
373+
```python
249374
def get_vowels(string):
250375
return [each for each in string if each in 'aeiou']
251376
get_vowels('foobar') # ['o', 'o', 'a']
252377
get_vowels('gym') # []
253378
```
379+
254380
### Length of Last Word in a string
255381
This method gets the length of last word in a given string.
256382
```
@@ -288,4 +414,17 @@ def countNegatives(self, grid: List[List[int]]) -> int:
288414
if n < 0:
289415
count += 1
290416
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /