Python Tutorial
Python Tutorial
Python Tutorial
Python Tutorial
In [103]: import sys
import keyword
import operator
from datetime import datetime
import os
Keywords
Keywords are the reserved words in Python and can't be used as an identifier
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'p
ass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 1/170
8/19/2020 Asif - Jupyter Notebook
In [16]: """
Correct way of defining an identifier
(Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an undersc
"""
val2 = 10
In [17]: val_ = 99
Comments in Python
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 2/170
8/19/2020 Asif - Jupyter Notebook
In [19]: # Multiple
# line
# comment
val1 = 10
In [20]: '''
Multiple
line
comment
'''
val1 = 10
In [21]: """
Multiple
line
comment
"""
val1 = 10
Statements
Out[27]: 30
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 3/170
8/19/2020 Asif - Jupyter Notebook
Indentation
Indentation refers to the spaces at the beginning of a code line. It is very important as Python uses indentation to indicate a block of code.If the
indentation is not correct we will endup with IndentationError error.
In [37]: p = 10
if p == 10:
print ('P is equal to 10') # correct indentation
P is equal to 10
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 4/170
8/19/2020 Asif - Jupyter Notebook
0
1
2
3
4
0
1
2
3
4
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 5/170
8/19/2020 Asif - Jupyter Notebook
In [48]: j=20
for i in range(0,5):
print(i) # inside the for loop
print(j) # outside the for loop
0
1
2
3
4
20
Docstrings
1) Docstrings provide a convenient way of associating documentation with functions, classes, methods or modules.
2) They appear right after the definition of a function, method, class, or module.
In [51]: square(2)
Out[51]: 4
Out[52]: 'Square Function :- This function will return the square of a number'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 6/170
8/19/2020 Asif - Jupyter Notebook
In [54]: evenodd(3)
Odd Number
In [55]: evenodd(2)
Even Number
In [56]: evenodd.__doc__
Out[56]: 'evenodd Function :- This function will test whether a numbr is Even or Odd'
Variables
A Python variable is a reserved memory location to store values.A variable is created the moment you first assign a value to it.
In [75]: p = 30
In [76]: '''
id() function returns the “identity” of the object.
The identity of an object - Is an integer
- Guaranteed to be unique
- Constant for this object during its lifetime.
'''
id(p)
Out[76]: 140735029552432
Out[77]: '0x7fff6d71a530'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 7/170
8/19/2020 Asif - Jupyter Notebook
In [94]: p = 20 #Creates an integer object with value 20 and assigns the variable p to point to that object.
q = 20 # Create new reference q which will point to value 20. p & q will be pointing to same memory location.
r = q # variable r will also point to the same location where p & q are pointing/
p , type(p), hex(id(p)) # Variable P is pointing to memory location '0x7fff6d71a3f0' where value 20 is stored
Out[94]: (20, int, '0x7fff6d71a3f0')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 8/170
8/19/2020 Asif - Jupyter Notebook
In [146]: p = 20
p = p + 10 # Variable Overwriting
p
Out[146]: 30
Variable Assigment
print(intvar)
print(floatvar)
print(strvar)
10
2.57
Python Language
Multiple Assignments
In [102]: intvar , floatvar , strvar = 10,2.57,"Python Language" # Using commas to separate variables and their corresponding value
print(intvar)
print(floatvar)
print(strvar)
10
2.57
Python Language
44 44 44 44
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 9/170
8/19/2020 Asif - Jupyter Notebook
Data Types
Numeric
In [135]: val1 = 10 # Integer data type
print(val1)
print(type(val1)) # type of object
print(sys.getsizeof(val1)) # size of integer object in bytes
print(val1, " is Integer?", isinstance(val1, int)) # val1 is an instance of int class
10
<class 'int'>
28
10 is Integer? True
92.78
<class 'float'>
24
92.78 is float? True
(25+10j)
<class 'complex'>
32
(25+10j) is complex? True
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 10/170
8/19/2020 Asif - Jupyter Notebook
Out[119]: 24
Out[138]: 32
Boolean
Boolean data type can have only two possible values true or false.
In [143]: print(type(bool1))
<class 'bool'>
In [144]: print(type(bool2))
<class 'bool'>
Out[148]: True
In [235]: bool(0)
Out[235]: False
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 11/170
8/19/2020 Asif - Jupyter Notebook
In [236]: bool(1)
Out[236]: True
In [237]: bool(None)
Out[237]: False
Out[238]: False
Strings
String Creation
print(str1)
HELLO PYTHON
Hello World
Hello World
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 12/170
8/19/2020 Asif - Jupyter Notebook
Hello
World
Hello
World
Out[200]: 35
String Indexing
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 13/170
8/19/2020 Asif - Jupyter Notebook
In [201]: str1
Out[201]: 'HELLO PYTHON'
Out[202]: 'H'
Out[203]: 'N'
Out[205]: 'P'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 14/170
8/19/2020 Asif - Jupyter Notebook
In [206]: str1[5]
String Slicing
In [207]: str1[0:5] # String slicing - Fetch all characters from 0 to 5 index location excluding the character at loc 5.
Out[207]: 'HELLO'
In [208]: str1[6:12] # String slicing - Retreive all characters between 6 - 12 index loc excluding index loc 12.
Out[208]: 'PYTHON'
Out[209]: 'THON'
Out[210]: 'PYTHON'
Out[211]: 'HELL'
In [213]: str1
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 15/170
8/19/2020 Asif - Jupyter Notebook
In [214]: #Strings are immutable which means elements of a string cannot be changed once they have been assigned.
str1[0:5] = 'HOLAA'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-214-ea670ff3ec72> in <module>
1 #Strings are immutable which means elements of a string cannot be changed once they have been assigned.
----> 2 str1[0:5] = 'HOLAA'
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-215-7fcc0cc83dcc> in <module>
1 del str1 # Delete a string
----> 2 print(srt1)
String concatenation
HelloAsif
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 16/170
8/19/2020 Asif - Jupyter Notebook
Hello Asif
In [219]: # Iteration
for i in mystr1:
print(i)
H
e
l
l
o
E
v
e
r
y
o
n
e
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 17/170
8/19/2020 Asif - Jupyter Notebook
(0, 'H')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
(5, ' ')
(6, 'E')
(7, 'v')
(8, 'e')
(9, 'r')
(10, 'y')
(11, 'o')
(12, 'n')
(13, 'e')
In [221]: list(enumerate(mystr1)) # Enumerate method adds a counter to an iterable and returns it in a form of enumerate object.
Out[221]: [(0, 'H'),
(1, 'e'),
(2, 'l'),
(3, 'l'),
(4, 'o'),
(5, ' '),
(6, 'E'),
(7, 'v'),
(8, 'e'),
(9, 'r'),
(10, 'y'),
(11, 'o'),
(12, 'n'),
(13, 'e')]
String Membership
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 18/170
8/19/2020 Asif - Jupyter Notebook
print ('Hello' in mystr1) # Check whether substring "Hello" is present in string "mysrt1"
print ('Everyone' in mystr1) # Check whether substring "Everyone" is present in string "mysrt1"
print ('Hi' in mystr1) # Check whether substring "Hi" is present in string "mysrt1"
True
True
False
String Partitioning
In [256]: """
The partition() method searches for a specified string and splits the string into a tuple containing three elements.
- The first element contains the part before the argument string.
- The third element contains the part after the argument string.
"""
('Natural language processing with Python ', 'and', ' R and Java')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 19/170
8/19/2020 Asif - Jupyter Notebook
In [257]: """
The rpartition() method searches for the last occurence of the specified string and splits the string into a tuple
containing three elements.
- The first element contains the part before the argument string.
- The third element contains the part after the argument string.
"""
('Natural language processing with Python and R ', 'and', ' Java')
String Functions
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 20/170
8/19/2020 Asif - Jupyter Notebook
In [273]: mystr2.strip('*') # Removes all '*' characters from begining & end of the string
In [274]: mystr2.rstrip('*') # Removes all '*' characters at the end of the string
In [275]: mystr2.lstrip('*') # Removes all '*' characters at the begining of the string
In [280]: mystr2.replace(" " , "") # Remove all whitespaces using replace function
Out[280]: 'HelloEveryone'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 21/170
8/19/2020 Asif - Jupyter Notebook
In [232]: mystr5.startswith("one") # Return boolean value True if string starts with "one"
Out[232]: True
In [233]: mystr5.endswith("three") # Return boolean value True if string ends with "three"
Out[233]: True
In [234]: mystr4 = "one two three four one two two three five five six seven six seven one one one ten eight ten nine eleven ten te
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 22/170
8/19/2020 Asif - Jupyter Notebook
Out[235]: ['one',
'two',
'three',
'four',
'one',
'two',
'two',
'three',
'five',
'five',
'six',
'seven',
'six',
'seven',
'one',
'one',
'one',
'ten',
'eight',
'ten',
'nine',
'eleven',
'ten',
'ten',
'nine']
print(res.format(item1,item2,item3))
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 23/170
8/19/2020 Asif - Jupyter Notebook
res = "Cost of item3 , item2 and item1 are {2} , {1} and {0}"
print(res.format(item1,item2,item3))
WELCOME EVERYONE
WELCOME EVERYONE
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 24/170
8/19/2020 Asif - Jupyter Notebook
19
19
False
True
True
True
True
True
False
False
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 25/170
8/19/2020 Asif - Jupyter Notebook
False
True
False
False
True
False
False
True
In [258]: str6 = "one two three four one two two three five five six one ten eight ten nine eleven ten ten nine"
51
print(loc)
51
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 26/170
8/19/2020 Asif - Jupyter Notebook
txt.rstrip()
txt.lstrip()
Out[265]: 'abc def ghi '
txt.strip()
List
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 27/170
8/19/2020 Asif - Jupyter Notebook
2) We can have different data types under a list. E.g we can have integer, float and string items in a same list.
List Creation
In [491]: print(type(list1))
<class 'list'>
List Indexing
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 28/170
8/19/2020 Asif - Jupyter Notebook
Out[432]: 10
Out[433]: 'one'
In [434]: list4[0][0] # Nested indexing - Access the first character of the first list element
Out[434]: 'o'
Out[435]: 'three'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 29/170
8/19/2020 Asif - Jupyter Notebook
List Slicing
In [437]: mylist = ['one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' , 'eight']
In [438]: mylist[0:3] # Return all items from 0th to 3rd index location excluding the item at loc 3.
In [439]: mylist[2:5] # List all items from 2nd to 5th index location excluding the item at loc 5.
Out[439]: ['three', 'four', 'five']
Out[444]: 'eight'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 30/170
8/19/2020 Asif - Jupyter Notebook
In [446]: mylist
Out[447]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 31/170
8/19/2020 Asif - Jupyter Notebook
Out[455]: []
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 32/170
8/19/2020 Asif - Jupyter Notebook
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-456-50c7849aa2cb> in <module>
1 del mylist # Delete the whole list
----> 2 mylist
Copy List
In [457]: mylist = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
In [459]: id(mylist) , id(mylist1) # The address of both mylist & mylist1 will be the same as both are pointing to same list.
In [461]: id(mylist2) # The address of mylist2 will be different from mylist because mylist2 is pointing to the copy of the existin
Out[461]: 1537345955016
In [462]: mylist[0] = 1
In [463]: mylist
Out[463]: [1, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 33/170
8/19/2020 Asif - Jupyter Notebook
In [464]: mylist1 # mylist1 will be also impacted as it is pointing to the same list
Out[464]: [1, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
In [465]: mylist2 # Copy of list won't be impacted due to changes made on the original list
Out[465]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
Join Lists
List Membership
In [469]: list1
Out[470]: True
Out[471]: False
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 34/170
8/19/2020 Asif - Jupyter Notebook
In [474]: list1
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 35/170
8/19/2020 Asif - Jupyter Notebook
In [585]: mylist4
In [481]: list1
Out[481]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']
one
two
three
four
five
six
seven
eight
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 36/170
8/19/2020 Asif - Jupyter Notebook
(0, 'one')
(1, 'two')
(2, 'three')
(3, 'four')
(4, 'five')
(5, 'six')
(6, 'seven')
(7, 'eight')
Count
In [485]: list10 =['one', 'two', 'three', 'four', 'one', 'one', 'two', 'three']
Out[487]: 2
All / Any
The any() function returns True if any element in the list is True. If not, any() returns False.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 37/170
8/19/2020 Asif - Jupyter Notebook
In [816]: L1 = [1,2,3,4,0]
Out[817]: False
In [818]: any(L1) # Will Return True as we have items in the list with True value
Out[818]: True
In [819]: L2 = [1,2,3,4,True,False]
In [821]: any(L2) # Will Return True as we have items in the list with True value
Out[821]: True
In [822]: L3 = [1,2,3,True]
In [823]: all(L3) # Will return True as all items in the list are True
Out[823]: True
In [824]: any(L3) # Will Return True as we have items in the list with True value
Out[824]: True
List Comprehensions
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 38/170
8/19/2020 Asif - Jupyter Notebook
In [289]: mylist1 = [ i for i in range(40) if i % 2 == 0] # Display all even numbers between 0 - 40 using List Comprehension
mylist1
Out[289]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
In [290]: mylist2 = [ i for i in range(40) if i % 2 == 1] # Display all odd numbers between 0 - 40 using List Comprehension
mylist2
Out[290]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]
In [325]: mylist3 = [num**2 for num in range(10)] # calculate square of all numbers between 0 - 10 using List Comprehension
mylist3
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 39/170
8/19/2020 Asif - Jupyter Notebook
In [299]: #List all numbers divisible by 3 , 9 & 12 using nested "if" with List Comprehension
mylist4 = [i for i in range(200) if i % 3 == 0 if i % 9 == 0 if i % 12 == 0]
mylist4
0 is Even Number
1 is odd number
2 is Even Number
3 is odd number
4 is Even Number
5 is odd number
6 is Even Number
7 is odd number
8 is Even Number
9 is odd number
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 40/170
8/19/2020 Asif - Jupyter Notebook
Out[316]: ['O',
'n',
'e',
't',
'w',
'o',
't',
'h',
'r',
'e',
'e',
'f',
'o',
'u',
'r',
'f',
'i',
'v',
'e',
's',
'i',
'x']
Tuples
1. Tuple is similar to List except that the objects in tuple are immutable which means we cannot change the elements of a tuple once assigned.
2. When we do not want to change the data over time, tuple is a preferred data type.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
Tuple Creation
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 41/170
8/19/2020 Asif - Jupyter Notebook
Out[540]: 6
Tuple Indexing
Out[542]: 'one'
In [543]: tup4[0][0] # Nested indexing - Access the first character of the first tuple element
Out[543]: 'o'
Out[544]: 'three'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 42/170
8/19/2020 Asif - Jupyter Notebook
Tuple Slicing
In [560]: mytuple = ('one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' , 'eight')
In [547]: mytuple[0:3] # Return all items from 0th to 3rd index location excluding the item at loc 3.
In [548]: mytuple[2:5] # List all items from 2nd to 5th index location excluding the item at loc 5.
Out[548]: ('three', 'four', 'five')
Out[553]: 'eight'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 43/170
8/19/2020 Asif - Jupyter Notebook
In [555]: mytuple
In [556]: del mytuple[0] # Tuples are immutable which means we can't DELETE tuple items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-556-667a276aa503> in <module>
----> 1 del mytuple[0]
In [557]: mytuple[0] = 1 # Tuples are immutable which means we can't CHANGE tuple items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-557-4cf492702bfd> in <module>
----> 1 mytuple[0] = 1
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 44/170
8/19/2020 Asif - Jupyter Notebook
In [570]: mytuple
one
two
three
four
five
six
seven
eight
(0, 'one')
(1, 'two')
(2, 'three')
(3, 'four')
(4, 'five')
(5, 'six')
(6, 'seven')
(7, 'eight')
Count
In [573]: mytuple1 =('one', 'two', 'three', 'four', 'one', 'one', 'two', 'three')
Out[574]: 3
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 45/170
8/19/2020 Asif - Jupyter Notebook
Out[575]: 2
Out[576]: 1
Tuple Membership
In [577]: mytuple
Out[579]: False
Index Position
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 46/170
8/19/2020 Asif - Jupyter Notebook
In [586]: mytuple
Out[590]: 4
In [591]: mytuple1
Out[593]: 0
Sorting
In [595]: sorted(mytuple2) # Returns a new sorted list and doesn't change original tuple
Sets
1) Unordered & Unindexed collection of items.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 47/170
8/19/2020 Asif - Jupyter Notebook
Set Creation
Out[635]: 5
Out[636]: {1, 2, 3, 4, 5}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 48/170
8/19/2020 Asif - Jupyter Notebook
In [640]: myset3 = {10,20, "Hola", [11, 22, 32]} # set doesn't allow mutable items like lists
myset3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-640-d23fdc3a319e> in <module>
----> 1 myset3 = {10,20, "Hola", [11, 22, 32]} # set doesn't allow mutable items like lists
2 myset3
<class 'set'>
In [776]: myset = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'}
for i in myset:
print(i)
eight
one
seven
three
five
two
six
four
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 49/170
8/19/2020 Asif - Jupyter Notebook
(0, 'eight')
(1, 'one')
(2, 'seven')
(3, 'three')
(4, 'five')
(5, 'two')
(6, 'six')
(7, 'four')
Set Membership
In [675]: myset
Out[676]: True
Out[677]: False
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 50/170
8/19/2020 Asif - Jupyter Notebook
In [680]: myset
Out[681]: {'NINE', 'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}
In [683]: myset.update(['TEN' , 'ELEVEN' , 'TWELVE']) # Add multiple item to a set using update() method
myset
Out[683]: {'ELEVEN',
'NINE',
'TEN',
'TWELVE',
'eight',
'five',
'four',
'one',
'seven',
'six',
'three',
'two'}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 51/170
8/19/2020 Asif - Jupyter Notebook
Out[684]: {'ELEVEN',
'TEN',
'TWELVE',
'eight',
'five',
'four',
'one',
'seven',
'six',
'three',
'two'}
Out[685]: {'ELEVEN',
'TWELVE',
'eight',
'five',
'four',
'one',
'seven',
'six',
'three',
'two'}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 52/170
8/19/2020 Asif - Jupyter Notebook
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-689-0912ea1b8932> in <module>
1 del myset
----> 2 myset
Copy Set
In [705]: myset = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'}
myset
In [707]: id(myset) , id(myset1) # The address of both myset & myset1 will be the same as both are pointing to same set.
Out[707]: (1537349033320, 1537349033320)
In [710]: id(my_set) # The address of my_set will be different from myset because my_set is pointing to the copy of the existing se
Out[710]: 1537352902024
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 53/170
8/19/2020 Asif - Jupyter Notebook
In [711]: myset.add('nine')
myset
Out[711]: {'eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two'}
In [712]: myset1 # myset1 will be also impacted as it is pointing to the same Set
Out[712]: {'eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two'}
In [713]: my_set # Copy of the set won't be impacted due to changes made on the original Set.
Set Operation
Union
In [757]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
C = {8,9,10}
Out[758]: {1, 2, 3, 4, 5, 6, 7, 8}
Out[759]: {1, 2, 3, 4, 5, 6, 7, 8}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 54/170
8/19/2020 Asif - Jupyter Notebook
In [761]: """
Updates the set calling the update() method with union of A , B & C.
For below example Set A will be updated with union of A,B & C.
"""
A.update(B,C)
A
Out[761]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Intersection
In [762]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
Out[763]: {4, 5}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 55/170
8/19/2020 Asif - Jupyter Notebook
In [765]: """
Updates the set calling the intersection_update() method with the intersection of sets.
For below example Set A will be updated with the intersection of A & B.
"""
A.intersection_update(B)
A
Out[765]: {4, 5}
Difference
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 56/170
8/19/2020 Asif - Jupyter Notebook
In [766]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
Out[768]: {1, 2, 3}
In [770]: B.difference(A)
Out[770]: {6, 7, 8}
In [771]: """
Updates the set calling the difference_update() method with the difference of sets.
For below example Set B will be updated with the difference of B & A.
"""
B.difference_update(A)
B
Out[771]: {6, 7, 8}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 57/170
8/19/2020 Asif - Jupyter Notebook
Symmetric Difference
In [772]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
In [773]: A ^ B # Symmetric difference (Set of elements in A and B but not in both. "EXCLUDING THE INTERSECTION").
Out[773]: {1, 2, 3, 6, 7, 8}
Out[774]: {1, 2, 3, 6, 7, 8}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 58/170
8/19/2020 Asif - Jupyter Notebook
In [775]: """
Updates the set calling the symmetric_difference_update() method with the symmetric difference of sets.
For below example Set A will be updated with the symmetric difference of A & B.
"""
A.symmetric_difference_update(B)
A
Out[775]: {1, 2, 3, 6, 7, 8}
In [784]: A = {1,2,3,4,5,6,7,8,9}
B = {3,4,5,6,7,8}
C = {10,20,30,40}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 59/170
8/19/2020 Asif - Jupyter Notebook
In [785]: B.issubset(A) # Set B is said to be the subset of set A if all elements of B are in A.
Out[785]: True
In [786]: A.issuperset(B) # Set A is said to be the superset of set B if all elements of B are in A.
Out[786]: True
In [787]: C.isdisjoint(A) # Two sets are said to be disjoint sets if they have no common elements.
Out[787]: True
In [788]: B.isdisjoint(A) # Two sets are said to be disjoint sets if they have no common elements.
Out[788]: False
In [789]: A
Out[789]: {1, 2, 3, 4, 5, 6, 7, 8, 9}
In [790]: sum(A)
Out[790]: 45
In [791]: max(A)
Out[791]: 9
In [792]: min(A)
Out[792]: 1
In [793]: len(A)
Out[793]: 9
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 60/170
8/19/2020 Asif - Jupyter Notebook
In [795]: list(enumerate(A))
Out[795]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
In [798]: D= sorted(A,reverse=True)
D
Out[798]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
In [799]: sorted(D)
Out[799]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary
Dictionary is a mutable data type in Python.
A python dictionary is a collection of key and value pairs separated by a colon (:) & enclosed in curly braces {}.
Keys must be unique in a dictionary, duplicate values are allowed.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 61/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 62/170
8/19/2020 Asif - Jupyter Notebook
Create Dictionary
Out[947]: {}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 63/170
8/19/2020 Asif - Jupyter Notebook
In [955]: mydict = {1:'one' , 2:'two' , 'A':['asif' , 'john' , 'Maria']} # dictionary with mixed keys
mydict
In [956]: mydict = {1:'one' , 2:'two' , 'A':['asif' , 'john' , 'Maria'], 'B':('Bat' , 'cat' , 'hat')} # dictionary with mixed keys
mydict
In [1]: mydict = {1:'one' , 2:'two' , 'A':{'Name':'asif' , 'Age' :20}, 'B':('Bat' , 'cat' , 'hat')} # dictionary with mixed keys
mydict
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 64/170
8/19/2020 Asif - Jupyter Notebook
In [960]: value.append(40)
mydict3
Accessing Items
Out[962]: 'one'
Out[963]: 'one'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 65/170
8/19/2020 Asif - Jupyter Notebook
Out[966]: 'Analyst'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 66/170
8/19/2020 Asif - Jupyter Notebook
In [973]: mydict1
In [975]: mydict1.clear() # Delete all items of the dictionary using clear method
mydict1
Out[975]: {}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 67/170
8/19/2020 Asif - Jupyter Notebook
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-976-da2fba4eca0f> in <module>
1 del mydict1 # Delete the dictionary object
----> 2 mydict1
Copy Dictionary
In [979]: id(mydict) , id(mydict1) # The address of both mydict & mydict1 will be the same as both are pointing to same dictionary
In [981]: id(mydict2) # The address of mydict2 will be different from mydict because mydict2 is pointing to the copy of the existin
Out[981]: 1537345875784
In [983]: mydict
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 68/170
8/19/2020 Asif - Jupyter Notebook
In [984]: mydict1 # mydict1 will be also impacted as it is pointing to the same dictionary
In [985]: mydict2 # Copy of list won't be impacted due to the changes made in the original dictionary
In [986]: mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' : 'Hilsinki' , 'Job': 'Analyst'}
mydict1
Name : Asif
ID : 12345
DOB : 1991
Address : Hilsinki
Job : Analyst
Asif
12345
1991
Hilsinki
Analyst
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 69/170
8/19/2020 Asif - Jupyter Notebook
Dictionary Membership
Out[990]: True
In [991]: 'Asif' in mydict1 # Membership test can be only done for keys.
Out[991]: False
Out[992]: True
Out[993]: False
All / Any
The any() function returns True if any key of the dictionary is True. If not, any() returns False.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 70/170
8/19/2020 Asif - Jupyter Notebook
Out[996]: True
In [997]: any(mydict1) # Will Return True as we have items in the dictionary with True value
Out[997]: True
Out[999]: False
In [1000]: any(mydict1) # Will Return True as we have items in the dictionary with True value
Out[1000]: True
Dictionary Comprehension
In [323]: double = {i:i*2 for i in range(10)} #double each value using dict comprehension
double
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 71/170
8/19/2020 Asif - Jupyter Notebook
mydict = {k:v for (k,v) in zip(key,value)} # using dict comprehension to create dictionary
mydict
Out[329]: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
Out[332]: {'a': 1.0, 'b': 2.0, 'c': 3.0, 'd': 4.0, 'e': 5.0}
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 72/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 73/170
8/19/2020 Asif - Jupyter Notebook
In [61]: mystr4 = "one two three four one two two three five five six seven six seven one one one ten eight ten nine eleven ten te
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 74/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 75/170
8/19/2020 Asif - Jupyter Notebook
{'nine': 2, 'one': 5, 'eight': 1, 'two': 3, 'seven': 2, 'ten': 4, 'four': 1, 'five': 2, 'three': 2, 'eleven': 1, 'six':
2}
Operators
Operators are special symbols in Python which are used to perform operations on variables/values.
Arithmetic Operators
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 76/170
8/19/2020 Asif - Jupyter Notebook
In [81]: a = 5
b = 2
x = 'Asif'
y = 'Bhat'
# Addition
c = a + b
print('Addition of {} and {} will give :- {}\n'.format(a,b,c))
# Subtraction
c = a - b
print('Subtracting {} from {} will give :- {}\n'.format(b,a,c))
# Multiplication
c = a * b
print('Multiplying {} and {} will give :- {}\n'.format(a,b,c))
# Division
c = a / b
print('Dividing {} by {} will give :- {}\n'.format(a,b,c))
# Power
c = a ** b
print('{} raised to the power {} will give :- {}\n'.format(a,b,c))
# Division(floor)
c = a // b
print('Floor division of {} by {} will give :- {}\n'.format(a,b,c))
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 77/170
8/19/2020 Asif - Jupyter Notebook
Comparison Operators
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 78/170
8/19/2020 Asif - Jupyter Notebook
In [84]: x = 20
y = 30
Is x equal to y :- False
In [87]: a = 'Asif'
b = 'Bhat'
c = 'Asif'
Logical Operators
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 79/170
8/19/2020 Asif - Jupyter Notebook
In [92]: x = True
y = False
print('Logical AND operation :- ',x and y) # True if both values are true
print('Logical OR operation :- ',x or y) # True if either of the values is true
print('NOT operation :- ',not x ) # True if operand is false
Bitwise operators
Assignment Operators
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 80/170
8/19/2020 Asif - Jupyter Notebook
In [120]: x = 10
x+=20 # x = x+20
print ('Add 20 to x :- ',x)
x-=20 # x = x-20
print ('subtract 20 from x :- ',x)
x/=10 # x = x/10
print ('Divide x by 10 :- ',x)
x*=10 # x = x/10
print ('Multiply x by 10 :- ',x)
x = int(x)
x**=2 # x = x/10
print ('x raised to the power 2 :- ',x)
x%=2
print ('Modulo Division :- ',x)
x = 20
x//=3
print ('Floor Division :- ',x)
x&=2
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 81/170
8/19/2020 Asif - Jupyter Notebook
x|=2
print('Bitwise OR :- ',x)
x^=2
print('Bitwise XOR :- ',x)
x = 10
x<<=2
print('Bitwise left shift operation',x)
x>>=2
print('Bitwise right shift operation',x)
Membership Operators
Membership Operators are used to test whether a value / variable is present in a sequence.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 82/170
8/19/2020 Asif - Jupyter Notebook
Functions
A function is a block of organized code written to carry out a specified task.
Functions help break our program into smaller and modular chunks for better readability.
Information can be passed into a function as arguments.
Parameters are specified after the function name inside the parentheses.
We can add as many parameters as we want. Parameters must be separated with a comma.
A function may or may not return data.
In Python a function is defined using the def keyword
Parameter VS Argument
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Syntax
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 83/170
8/19/2020
y Asif - Jupyter Notebook
Modularity
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 84/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 85/170
8/19/2020 Asif - Jupyter Notebook
myfunc()
Name :- Asif
User ID is :- asif123
Country :- India
square (10)
Out[586]: 100
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 86/170
8/19/2020 Asif - Jupyter Notebook
even_odd(3)
even_odd(4)
print(even_odd.__doc__) # Print function documentation string
3 is odd number
4 is even number
This function will check whether a number is even or odd
fullname(lastname = 'Bhat' , middlename='Ali' , firstname='Asif') # Keyword Arguments. Order of the arguments does not ma
In [592]: fullname ('Asif') # This will throw error as function is expecting 3 arguments.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-592-d194f8b98253> in <module>
----> 1 fullname ('Asif')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 87/170
8/19/2020 Asif - Jupyter Notebook
myfunc() # When a function is called without an argument it will use default value
def myfunc():
print(var1) # Value 100 will be displayed due to global scope of var1
myfunc()
print(var1)
100
100
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 88/170
8/19/2020 Asif - Jupyter Notebook
def myfunc2():
print(var2) # This will throw error because var2 has a local scope. Var2 is only accessible in myfunc1()
myfunc1()
myfunc2()
10
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-27-6a1c34e80ca2> in <module>
8
9 myfunc1()
---> 10 myfunc2()
<ipython-input-27-6a1c34e80ca2> in myfunc2()
5
6 def myfunc2():
----> 7 print(var2) # Value 100 will be displayed due to global scope of var1
8
9 myfunc1()
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 89/170
8/19/2020 Asif - Jupyter Notebook
def myfunc():
var1 = 99 # Local scope
print(var1)
myfunc()
print(var1) # The original value of var1 (100) will be retained due to global scope.
99
100
def myfunc(list1):
del list1[0]
"List1" before calling the function:- [11, 22, 33, 44, 55]
"List1" after calling the function:- [22, 33, 44, 55]
def myfunc(list1):
list1.append(100)
"List1" before calling the function:- [11, 22, 33, 44, 55]
"List1" after calling the function:- [11, 22, 33, 44, 55, 100]
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 90/170
8/19/2020 Asif - Jupyter Notebook
def myfunc(list1):
list1 = [10,100,1000,10000] # link of 'list1' with previous object is broken now as new object is assigned to 'list1
"List1" before calling the function:- [11, 22, 33, 44, 55]
"List1" after calling the function:- [11, 22, 33, 44, 55]
a = 10
b = 20
swap(a,b)
a,b
Out[45]: (10, 20)
In [601]: def factorial(num): # Calculate factorial of a number using recursive function call.
if num <=1 :
return 1
else:
return num * factorial(num-1)
factorial(4)
Out[601]: 24
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 91/170
8/19/2020 Asif - Jupyter Notebook
Out[618]: 15
for i in range(nums):
print(fiboacci(i)) # Generate Fibonacci series
*args
When we are not sure about the number of arguments being passed to a function then we can use *args as function parameter.
*args allow us to pass the variable number of Non Keyword Arguments to function.
We can simply use an asterisk * before the parameter name to pass variable length arguments.
The arguments are always passed as a tuple.
We can rename it to anything as long as it is preceded by a single asterisk (*). It's best practice to keep naming it args to make it immediately
recognizable.
**kwargs
**kwargs allows us to pass the variable number of Keyword Arguments to the function.
We can simply use an double asterisk ** before the parameter name to pass variable length arguments.
The arguments are passed as a dictionary.
We can rename it to anything as long as it is preceded by a double asterisk (**). It's best practice to keep naming it kwargs to make it
immediately recognizable.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 93/170
8/19/2020 Asif - Jupyter Notebook
60
In [577]: print(add(1,2,3,4)) '''This will throw below error as this function will only take two argumengts.
If we want to make argument list dynamic then *args wil come in picture'''
^
SyntaxError: invalid syntax
my_list = [2, 3]
some_args(1, *my_list)
arg_1: 1
arg_2: 2
arg_3: 3
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 94/170
8/19/2020 Asif - Jupyter Notebook
print(add(1,2,3))
print(add(1,2,3,4)) # *args will take dynamic argument list. So add() function will perform addition of any number of ar
print(add(1,2,3,4,5))
print(add(1,2,3,4,5,6))
print(add(1,2,3,4,5,6,7))
6
10
15
21
28
add1(*list1) , add1(*tuple1) #tuple & list items will be passed as argument list and sum will be returned for both cases
Out[561]: (28, 28)
add1(*list1 , *list2 , *list3 , *list4 ) #All four lists are unpacked and each individual item is passed to add1() functi
Out[562]: 112
''' For the above example we have no idea about the parameters passed e.g 7412 , 41102 , 33 etc.
In such cases we can take help of Keyworded arguments (**kwargs) '''
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 95/170
8/19/2020 Asif - Jupyter Notebook
{'Name': 'Asif', 'ID': 7412, 'Pincode': 41102, 'Age': 33, 'Country': 'India', 'Language': 'Hindi'}
Name :- Asif
ID :- 7412
Pincode :- 41102
Age :- 33
Country :- India
Language :- Hindi
In [523]: mydict = {'Name': 'Asif', 'ID': 7412, 'Pincode': 41102, 'Age': 33, 'Country': 'India', 'Language': 'Hindi'}
UserDetails(**mydict)
Name :- Asif
ID :- 7412
Pincode :- 41102
Age :- 33
Country :- India
Language :- Hindi
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 96/170
8/19/2020 Asif - Jupyter Notebook
In [553]: def UserDetails(licenseNo, *args , phoneNo=0 , **kwargs): # Using all four arguments types
print('License No :- ', licenseNo)
j=''
for i in args:
j = j+i
print('Full Name :-',j)
print('Phone Number:- ',phoneNo)
for key,val in kwargs.items():
print("{} :- {}".format(key,val))
License No :- BHT145
Full Name :- Asif Ali Bhat
Phone Number:- 1234567890
Name :- Asif
ID :- 7412
Pincode :- 41102
Age :- 33
Country :- India
Language :- Hindi
In [554]: def UserDetails(licenseNo, *args , phoneNo=0, **kwargs): # Using all four arguments types. CORRECT ORDER
print('Nothing')
In [557]: def UserDetails(licenseNo, **kwargs , *args): # This will fail. *args MUST come before **kwargs in the argument list
print('Nothing')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 97/170
8/19/2020 Asif - Jupyter Notebook
In [564]: #The below function will fail. Default argument/positional argument (licenseNo) MUST come before Keyword argument(ID)
def UserDetails(ID = 1, licenseNo, *args):
print('Nothing')
Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned.
We use lambda functions when we require a nameless function for a short period of time.
Syntax:-
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 98/170
8/19/2020 Asif - Jupyter Notebook
Filter
Filter function filters the original iterable and passes the items that returns True for the function provided to filter.
Syntax:
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 99/170
8/19/2020 Asif - Jupyter Notebook
Map
The map() function applies a given function to each item of an iterable (list, tuple etc.) and returns a list of the results.
Returns : Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Syntax:
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 100/170
8/19/2020 Asif - Jupyter Notebook
Reduce
The reduce() function is defined in the functools python module.The reduce() function receives two arguments, a function and an iterable.
However, it doesn't return another iterable, instead it returns a single value.
Working:
1) Apply a function to the first two items in an iterable and generate a partial result.
2) The function is then called again with the result obtained in step 1 and the next value in the sequence. This process keeps on repeating until
there are items in the sequence.
Syntax:
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 101/170
8/19/2020 Asif - Jupyter Notebook
15
In [393]: product = lambda a, b : a * b #This lambda function takes two arguments (a,b) and returns their product (a*b).
print(product(5, 6))
30
In [394]: addition = lambda a, b, c : a + b + c #This lambda function takes three arguments (a,b,c) and returns their sum (a+b+c)
print(addition(5, 6, 2))
13
In [364]: res = (lambda *args: sum(args)) # This lambda function can take any number of arguments and return thier sum.
res(10,20) , res(10,20,30,40) , res(10,20,30,40,50,60,70)
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 102/170
8/19/2020 Asif - Jupyter Notebook
In [370]: res1 = (lambda **kwargs: sum(kwargs.values())) # This lambda function can take any number of arguments and return thier s
res1(a = 10 , b= 20 , c = 30) , res1(a = 10 , b= 20 , c = 30, d = 40 , e = 50)
In [386]: res1 = (lambda **kwargs: sum(kwargs.values())) # This lambda function can take any number of arguments and return thier s
res1(a = 10 , b= 20 , c = 30) , res1(a = 10 , b= 20 , c = 30, d = 40 , e = 50)
Out[386]: (60, 150)
# This lambda function can take any number of arguments and return thier product.
res1 = (lambda **kwargs: product(kwargs.values()))
res1(a = 10 , b= 20 , c = 30) , res1(a = 10 , b= 20 , c = 30, d = 40 , e = 50)
add10 = myfunc(10)
add20 = myfunc(20)
add30 = myfunc(30)
print(add10(5))
print(add20(5))
print(add30(5))
15
25
35
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 103/170
8/19/2020 Asif - Jupyter Notebook
def odd(n):
if n%2 ==1: return True
else: return False
odd_num = list(filter(odd,list1)) # This Filter function filters list1 and passes all odd numbers to filter().
odd_num
Out[437]: [1, 3, 5, 7, 9]
doubles = list(map(twice,odd_num)) # The map function will apply user defined "twice()" function on all items of the list
doubles
Out[439]: [2, 6, 10, 14, 18]
In [440]: doubles = list(map(lambda n:n*2,odd_num)) # This map function will double all items of the list using lambda function.
doubles
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 104/170
8/19/2020 Asif - Jupyter Notebook
def add(a,b):
return a+b
sum_all = reduce(add,doubles) # This reduce function will perform sum of all items in the list using user defined "add()
sum_all
Out[441]: 50
In [442]: #The below reduce() function will perform sum of all items in the list using lambda function.
sum_all = reduce(lambda a,b : a+b,doubles)
sum_all
Out[442]: 50
Out[448]: 50
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 105/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 106/170
8/19/2020 Asif - Jupyter Notebook
print('--------')
print(even)
print(odd)
print('--------')
upper = list(filter(lambda x: x.isupper() , list2)) # filter uppercase strings from the list
lower = list(filter(lambda x: x.islower() , list2)) # filter lowercase strings from the list
print(upper)
print(lower)
print('--------')
alpha = list(filter(lambda x:x.isalpha(), list3)) # filter character strings from the list
alphanum = list(filter(lambda x:x.isalnum(), list3)) # filtr numbers & character strings from the list
print(alpha)
print(numeric)
print(alphanum)
print('--------')
#Vowel Test
--------
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 107/170
8/19/2020 Asif - Jupyter Notebook
--------
['TWO', 'FOUR']
['one', 'three']
--------
['one']
['88', '99', '102']
['one', 'two2', 'three3', '88', '99', '102']
--------
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 108/170
8/19/2020 Asif - Jupyter Notebook
def double(x):
return x+x
def add(x,y):
return x+y
def square(x):
return x*x
print('---------------')
print(list(map(double, list1))) # Double each number using map & User defined function
print(list(map(add, list1, list2))) # add two items using map & User defined function
print(list(map(square, list1))) #Square numbers using map & User defined function
print('---------------')
print('---------------')
---------------
[2, 4, 6, 8]
[6, 8, 10, 12]
[1, 4, 9, 16]
---------------
[2, 4, 6, 8]
[6, 8, 10, 12]
[1, 4, 9, 16]
---------------
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 109/170
8/19/2020 Asif - Jupyter Notebook
concat_str = reduce(operator.add , ['Python' , ' ' , 'Rocks']) # Concatenate string using reduce
min_num = reduce(lambda a, b: a if a < b else b, list2) # Minimum number in the list using reduce () & lambda
max_num = reduce(lambda a, b: a if a > b else b, list2) # Maximum number in the list using reduce () & lambda
print(product)
print(add)
print(concat_str)
print(prod)
print(min_num)
print(max_num)
24
10
Python Rocks
Hello Hello Hello
1
4
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 110/170
8/19/2020 Asif - Jupyter Notebook
min_num = reduce(min_func, list2) # Minimum number in the list using reduce () & User defined min function
max_num = reduce(max_func, list2) # Maximum number in the list using reduce () & User defined min function
min_num , max_num
Out[461]: (1, 4)
In [474]: print('------')
print(reduce(lambda a, b: bool(a and b), [0, 0, 1, 0, 0])) # Returns True if all values in the list are True
print(reduce(lambda a, b: bool(a and b), [2, 3, 1, 5, 6])) # Returns True if all items in the list are True
print(reduce(lambda a, b: bool(a and b), [8, 9, 1, 0, 9])) # Returns True if all values in the list are True
print('------')
print(reduce(lambda a, b: bool(a or b), [0, 0, 0, 0, 0])) # Returns True if any item in the list is True
print(reduce(lambda a, b: bool(a or b), [2, 3, 1, 5, 6])) # Returns True if any item in the list is True
print(reduce(lambda a, b: bool(a or b), [8, 9, 1, 0, 9])) # Returns True if any item in the list is True
print('------')
------
False
True
False
------
False
True
True
------
Syntax
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 112/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 113/170
8/19/2020 Asif - Jupyter Notebook
10
print('Name :- ',emp1.name)
print('Employee ID :- ',emp1.empid)
emp1.greet()
Name :- Asif
Employee ID :- 34163
Thanks for joining ABC Company Asif!!
Out[71]: 'Basit'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 114/170
8/19/2020 Asif - Jupyter Notebook
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-72-b111c8b828fc> in <module>
1 del emp1.empid # Delete Object Properties
----> 2 emp1.empid
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-73-db2cb77ec9fb> in <module>
1 del emp1 # Delete the object
----> 2 emp1
print('Name :- ',emp2.name)
print('Employee ID :- ',emp2.empid)
emp2.greet()
Name :- Michael
Employee ID :- 34162
Thanks for joining ABC Company Michael!!
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 115/170
8/19/2020 Asif - Jupyter Notebook
Inheritance
Inheritance provides code reusability in the program because we can use an existing class (Super Class/ Parent Class / Base Class) to create a
new class (Sub Class / Child Class / Derived Class) instead of creating it from scratch.
The child class inherits data definitions and methods from the parent class which facilitates the reuse of features already available. The child
class can add few more definitions or redefine a base class method.
Inheritance comes into picture when a new class possesses the 'IS A' relationship with an existing class. E.g Student is a person. Hence person
is the base class and student is derived class.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 116/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 117/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 118/170
8/19/2020 Asif - Jupyter Notebook
def PersonInfo(self):
print('Name :- {}'.format(self.name))
print('Age :- {}'.format(self.age))
print('Gender :- {}'.format(self.gender))
def StudentInfo(self):
print('Student ID :- {}'.format(self.studentid))
print('Fees :- {}'.format(self.fees))
def TeacherInfo(self):
print('Employee ID :- {}'.format(self.empid))
print('Salary :- {}'.format(self.salary))
stud1.PersonInfo() # PersonInfo() method presnt in Parent Class will be accessible by child class
stud1.StudentInfo()
print()
Student Details
---------------
Name :- Asif
Age :- 24
Gender :- Male
Student ID :- 123
Fees :- 1200
Employee Details
---------------
Name :- Basit
Age :- 36
Gender :- Male
Employee ID :- 456
Salary :- 80000
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 120/170
8/19/2020 Asif - Jupyter Notebook
In [182]: # super() builtin function allows us to access methods of the base class.
def PersonInfo(self):
print('Name :- {}'.format(self.name))
print('Age :- {}'.format(self.age))
print('Gender :- {}'.format(self.gender))
def StudentInfo(self):
super().PersonInfo()
print('Student ID :- {}'.format(self.studentid))
print('Fees :- {}'.format(self.fees))
Name :- Asif
Age :- 24
Gender :- Male
Student ID :- 123
Fees :- 1200
Multi-level Inheritance
In this type of inheritance, a class can inherit from a child class or derived class.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 121/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 122/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 123/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 124/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 125/170
8/19/2020 Asif - Jupyter Notebook
def PersonInfo(self):
print('Name :- {}'.format(self.name))
print('Age :- {}'.format(self.age))
print('Gender :- {}'.format(self.gender))
def employeeInfo(self):
print('Employee ID :- {}'.format(self.empid))
print('Salary :- {}'.format(self.salary))
def FulltimeInfo(self):
print('Work Experience :- {}'.format(self.WorkExperience))
self.ContractExpiry = ContractExpiry
def ContractInfo(self):
print('Contract Expiry :- {}'.format(self.ContractExpiry))
print('\n \n')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 127/170
8/19/2020 Asif - Jupyter Notebook
Multiple Inheritance
Multiple inheritance is a feature in which a class (derived class) can inherit attributes and methods from more than one parent class.
The derived class inherits all the features of the base case.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 128/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 129/170
8/19/2020 Asif - Jupyter Notebook
# Super Class
class Mother:
def __init__(self):
self.mothername = str()
# Sub Class
class Son(Father, Mother):
name = str()
def show(self):
print('My Name :- ',self.name)
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son()
s1.name = 'Bill'
s1.fathername = "John"
s1.mothername = "Kristen"
s1.show()
My Name :- Bill
Father : John
Mother : Kristen
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 130/170
8/19/2020 Asif - Jupyter Notebook
class Time:
def __init__(self,time):
self.time = time
class timestamp(CurrentDate,CurrentTime):
def __init__(self,date,time):
CurrentDate.__init__(self,date)
CurrentTime.__init__(self,time)
DateTime = self.date + ' ' + self.time
print(DateTime)
2020-08-09 23:48:55
Method Overriding
Overriding is a very important part of object oreinted programming because it makes inheritance exploit its full power.
Overriding is the ability of a class (Sub Class / Child Class / Derived Class) to change the implementation of a method provided by one of its
parent classes.
When a method in a subclass has the same name, same parameter and same return type as a method in its super-class, then the method in
the subclass is said to override the method in the super-class.
The version of a method that is executed will be determined by the object that is used to invoke it.
If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass
is used to invoke the method, then the version in the child class will be executed.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 131/170
8/19/2020 Asif - Jupyter Notebook
def greet(self):
print("Hello Person")
def greet(self):
print("Hello Student")
Hello Student
Hello Person
Container
Containers are data structures that hold data values.
They support membership tests which means we can check whether a value exists in the container or not.
Generally containers provide a way to access the contained objects and to iterate over them.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 132/170
8/19/2020 Asif - Jupyter Notebook
Out[124]: True
In [128]: assert 'john' in list1 # If the condition returns true the program does nothing and move to the next line of code
In [127]: assert 'john1' in list1 # If the condition returns false, Assert will stop the program and throws an AssertionError.
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-127-f7bcea8c4682> in <module>
----> 1 assert 'john1' in list1
AssertionError:
In [131]: 'Asif' in mydict # Dictionary membership will always check the keys
Out[131]: False
In [132]: 'Name' in mydict # Dictionary membership will always check the keys
Out[132]: True
Out[133]: True
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 133/170
8/19/2020 Asif - Jupyter Notebook
Out[134]: True
An iterable object implements __iter()__ which is expected to return an iterator object. The iterator object uses the __next()__ method. Every
time next() is called next element in the iterator stream is returned. When there are no more elements available StopIteration exception is
encountered. So any object that has a __next()__ method is called an iterator.
Python lists, tuples, dictionaries and sets are all examples of iterable objects.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 134/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 135/170
8/19/2020 Asif - Jupyter Notebook
Asif
Basit
John
Michael
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-236-a2095e242a65> in <module>
5 print(next(list_iter))
6 print(next(list_iter))
----> 7 print(next(list_iter))
StopIteration:
Asif
Basit
John
Michael
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 136/170
8/19/2020 Asif - Jupyter Notebook
Asif
Basit
John
Michael
for i in mylist:
print(i)
Asif
Basit
John
Michael
for i in mytuple:
print(i)
Asif
Basit
John
Michael
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 137/170
8/19/2020 Asif - Jupyter Notebook
for i in mystr:
print(i)
H
e
l
l
o
P
y
t
h
o
n
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 138/170
8/19/2020 Asif - Jupyter Notebook
def __iter__(self):
self.num = 1
return self
def __next__(self):
if self.num <= 10:
val = self.num
self.num += 1
return val
else:
raise StopIteration
mynum = myiter()
iter1 = iter(mynum)
for i in iter1:
print(i)
1
2
3
4
5
6
7
8
9
10
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 139/170
8/19/2020 Asif - Jupyter Notebook
def __iter__(self):
self.num = 1
return self
def __next__(self):
if self.num <= 20 :
val = self.num
self.num += 2
return val
else:
raise StopIteration
myodd = myiter()
iter1 = iter(myodd)
for i in iter1:
print(i)
1
3
5
7
9
11
13
15
17
19
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 140/170
8/19/2020 Asif - Jupyter Notebook
class myfibonacci:
def __init__(self):
self.prev = 0
self.cur = 0
def __iter__(self):
self.prev = 0
self.cur = 1
return self
def __next__(self):
if self.cur <= 50:
val = self.cur
self.cur += self.prev
self.prev = val
return val
else:
raise StopIteration
myfibo = myfibonacci()
iter1 = iter(myfibo)
for i in iter1:
print(i)
1
1
2
3
5
8
13
21
34
Generator
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 141/170
8/19/2020 Asif - Jupyter Notebook
Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead of returning the entire
sequence at once.
The generator function cannot include the return keyword. If we include it then it will terminate the execution of the function.
The difference between yield and return is that once yield returns a value the function is paused and the control is transferred to the
caller.Local variables and their states are remembered between successive calls. In case of the return statement value is returned and the
execution of the function is terminated.
Methods like __iter()__ and __next()__ are implemented automatically in generator function.
Simple generators can be easily created using generator expressions. Generator expressions create anonymous generator functions like
lambda.
The syntax for generator expression is similar to that of a list comprehension but the only difference is square brackets are replaced with round
parentheses. Also list comprehension produces the entire list while the generator expression produces one item at a time which is more
memory efficient than list comprehension.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 142/170
8/19/2020 Asif - Jupyter Notebook
n += 1
yield n
n += 1
yield n
n += 1
yield n
n += 1
yield n
mygen1 = mygen()
print(next(mygen1))
print(next(mygen1))
print(next(mygen1))
print(next(mygen1))
print(next(mygen1)) #Function will terminate here as all 5 values have been returned.
print(next(mygen1)) # As function is already terminated, StopIteration is raised automatically.
1
2
3
4
5
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-258-4c1c399db6dd> in <module>
24 print(next(mygen1))
25 print(next(mygen1))
---> 26 print(next(mygen1))
StopIteration:
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 143/170
8/19/2020 Asif - Jupyter Notebook
In [272]: # Simple generator function that will generate natural numbers from 1 to 20.
def mygen():
for i in range(1,20):
yield i
mygen1 = mygen()
for i in mygen1:
print(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
In [274]: num = list(mygen()) # Store all values generated by generator function in a list
num
Out[274]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 144/170
8/19/2020 Asif - Jupyter Notebook
In [275]: # Simple generator function that will generate even numbers from 1 to 20.
def mygen():
for i in range(1,20):
if i%2 == 0:
yield i
mygen1 = mygen()
for i in mygen1:
print(i)
2
4
6
8
10
12
14
16
18
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 145/170
8/19/2020 Asif - Jupyter Notebook
In [276]: # This Generator function will generate ten numbers of fibonacci series.
def myfibo():
num1 , num2 = 0,1
count = 0
while count < 10:
yield num1
num1,num2 = num2,num1+num2
count+=1
fibo = myfibo()
for i in fibo:
print(i)
0
1
1
2
3
5
8
13
21
34
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 146/170
8/19/2020 Asif - Jupyter Notebook
In [282]: print(next(gen2))
print(next(gen2))
print(next(gen2))
print(next(gen2))
print(next(gen2))
1
4
9
16
25
In [288]: gen2 = (i for i in range(40) if i%2 == 0) # Generator expression to generate even numbers
gen2
for i in gen2:
print(i)
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
Decorator
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 147/170
8/19/2020
Decorator Asif - Jupyter Notebook
Decorator is very powerful and useful tool in Python as it allows us to wrap another function in order to extend the behavior of wrapped function
without permanently modifying it.
In Decorators functions are taken as the argument into another function and then called inside the wrapper function.
Advantages -
subtract(4,2)
subtract(2,4)
Result is :- 2
Result is :- -2
In [6]: ''' We now want subtract() function to always subtract lower number from higher one without modifying this function.
So when we pass (2,4) it should perform 4-2 not 2-4. To acheive this we will create a decorator function'''
def sub_decorator(func):
def wrapper(num1,num2):
if num1 < num2:
num1,num2 = num2,num1
return func(num1,num2)
return wrapper
sub = sub_decorator(subtract)
sub(2,4)
Result is :- 2
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 148/170
8/19/2020 Asif - Jupyter Notebook
In [20]: @sub_decorator # we can use @ syntax for decorating a function in one step
def subtract(num1 , num2):
res = num1 - num2
print('Result is :- ', res)
subtract(2,4)
Result is :- 2
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 149/170
8/19/2020 Asif - Jupyter Notebook
def InstallWindows():
print('Windows installation has started \n')
def InstallMac():
print('Mac installation has started \n')
InstallLinux()
InstallWindows()
InstallMac()
print()
''' Now suppose if we want to print message :- "Please accept terms & conditions" before every installation
then easy way will be to create one decorator function which will present this message instead of modifying all funct
def InstallDecorator(func):
def wrapper():
print('Please accept terms & conditions')
return func()
return wrapper()
@InstallDecorator
def InstallWindows():
print('Windows installation has started \n ')
@InstallDecorator
def InstallMac():
print('Mac installation has started \n')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 150/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 151/170
8/19/2020 Asif - Jupyter Notebook
def InstallDecorator1(func):
def wrapper():
print('Please accept terms & conditions...\n')
func()
return wrapper
def InstallDecorator2(func):
def wrapper():
print('Please enter correct license key...\n')
return func()
return wrapper
def InstallDecorator3(func):
def wrapper():
print('Please enter partitioning choice...\n')
return func()
return wrapper
@InstallDecorator1
@InstallDecorator2
@InstallDecorator3
def InstallLinux():
print('Linux installation has started \n')
InstallLinux()
File Management
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 152/170
8/19/2020
g Asif - Jupyter Notebook
Python has several built-in modules and functions for creating, reading, updating and deleting files.
Open File
Close File
In [73]: fileobj.close()
Read File
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 153/170
8/19/2020 Asif - Jupyter Notebook
Out[85]: 'Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead
of returning the entire sequence at once.\nIt is a special type of function which returns an iterator object.\nIn a gen
erator function, a yield statement is used rather than a return statement.\nThe generator function cannot include the r
eturn keyword. If we include it then it will terminate the execution of the function.\nThe difference between yield and
return is that once yield returns a value the function is paused and the control is transferred to the caller.Local var
iables and their states are remembered between successive calls. In case of the return statement value is returned and
the execution of the function is terminated.\nMethods like __iter()__ and __next()__ are implemented automatically in g
enerator function.\nSimple generators can be easily created using generator expressions. Generator expressions create a
nonymous generator functions like lambda.\nThe syntax for generator expression is similar to that of a list comprehensi
on but the only difference is square brackets are replaced with round parentheses. Also list comprehension produces the
entire list while the generator expression produces one item at a time which is more memory efficient than list compreh
ension.'
In [86]: fileobj.read() #File cursor is already at the end of the file so it won't be able to read anything.
Out[86]: ''
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 154/170
8/19/2020 Asif - Jupyter Notebook
Out[88]: 'generators are easy way of creating iterators. It generates values one at a time from a given sequence instead of retu
rning the entire sequence at once.\nIt is a special type of function which returns an iterator object.\nIn a generator
function, a yield statement is used rather than a return statement.\nThe generator function cannot include the return k
eyword. If we include it then it will terminate the execution of the function.\nThe difference between yield and return
is that once yield returns a value the function is paused and the control is transferred to the caller.Local variables
and their states are remembered between successive calls. In case of the return statement value is returned and the exe
cution of the function is terminated.\nMethods like __iter()__ and __next()__ are implemented automatically in generato
r function.\nSimple generators can be easily created using generator expressions. Generator expressions create anonymou
s generator functions like lambda.\nThe syntax for generator expression is similar to that of a list comprehension but
the only difference is square brackets are replaced with round parentheses. Also list comprehension produces the entire
list while the generator expression produces one item at a time which is more memory efficient than list comprehensio
n.'
In [89]: fileobj.seek(0)
Out[90]: 16
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 155/170
8/19/2020 Asif - Jupyter Notebook
In [91]: fileobj.seek(0)
Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead o
f returning the entire sequence at once.
In [92]: fileobj.seek(0)
Out[92]: ['Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead
of returning the entire sequence at once.\n',
'It is a special type of function which returns an iterator object.\n',
'In a generator function, a yield statement is used rather than a return statement.\n',
'The generator function cannot include the return keyword. If we include it then it will terminate the execution of th
e function.\n',
'The difference between yield and return is that once yield returns a value the function is paused and the control is
transferred to the caller.Local variables and their states are remembered between successive calls. In case of the retu
rn statement value is returned and the execution of the function is terminated.\n',
'Methods like __iter()__ and __next()__ are implemented automatically in generator function.\n',
'Simple generators can be easily created using generator expressions. Generator expressions create anonymous generator
functions like lambda.\n',
'The syntax for generator expression is similar to that of a list comprehension but the only difference is square brac
kets are replaced with round parentheses. Also list comprehension produces the entire list while the generator expressi
on produces one item at a time which is more memory efficient than list comprehension.']
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 156/170
8/19/2020 Asif - Jupyter Notebook
count = 0
for i in range(5):
if (count < 5):
print(fileobj.readline())
else:
break
count+=1
Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead o
f returning the entire sequence at once.
The generator function cannot include the return keyword. If we include it then it will terminate the execution of the
function.
The difference between yield and return is that once yield returns a value the function is paused and the control is tr
ansferred to the caller.Local variables and their states are remembered between successive calls. In case of the return
statement value is returned and the execution of the function is terminated.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 157/170
8/19/2020 Asif - Jupyter Notebook
count = 0
for i in fileobj.readlines():
if (count < 5):
print(i)
else:
break
count+=1
Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead o
f returning the entire sequence at once.
The generator function cannot include the return keyword. If we include it then it will terminate the execution of the
function.
The difference between yield and return is that once yield returns a value the function is paused and the control is tr
ansferred to the caller.Local variables and their states are remembered between successive calls. In case of the return
statement value is returned and the execution of the function is terminated.
Write File
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 158/170
8/19/2020 Asif - Jupyter Notebook
fileobj.write('THIS IS THE NEW CONTENT APPENDED IN THE FILE') # Append content to the file
fileobj.close()
fileobj = open('test1.txt')
fileobj.read()
Out[95]: 'Python generators are easy way of creating iterators. It generates values one at a time from a given sequence instead
of returning the entire sequence at once.\nIt is a special type of function which returns an iterator object.\nIn a gen
erator function, a yield statement is used rather than a return statement.\nThe generator function cannot include the r
eturn keyword. If we include it then it will terminate the execution of the function.\nThe difference between yield and
return is that once yield returns a value the function is paused and the control is transferred to the caller.Local var
iables and their states are remembered between successive calls. In case of the return statement value is returned and
the execution of the function is terminated.\nMethods like __iter()__ and __next()__ are implemented automatically in g
enerator function.\nSimple generators can be easily created using generator expressions. Generator expressions create a
nonymous generator functions like lambda.\nThe syntax for generator expression is similar to that of a list comprehensi
on but the only difference is square brackets are replaced with round parentheses. Also list comprehension produces the
entire list while the generator expression produces one item at a time which is more memory efficient than list compreh
ension.THIS IS THE NEW CONTENT APPENDED IN THE FILE'
fileobj.write("NEW CONTENT ADDED IN THE FILE. PREVIOUS CONTENT HAS BEEN OVERWRITTEN") # overwrite the content in the file
fileobj.close()
fileobj = open('test1.txt')
fileobj.read()
Out[96]: 'NEW CONTENT ADDED IN THE FILE. PREVIOUS CONTENT HAS BEEN OVERWRITTEN'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 159/170
8/19/2020 Asif - Jupyter Notebook
fileobj.write("First Line\n")
fileobj.write("Second Line\n")
fileobj.write("Third Line\n")
fileobj.write("Fourth Line\n")
fileobj.write("Fifth Line\n")
fileobj.close()
fileobj = open('test2.txt')
fileobj.readlines()
Delete file
In [116]: os.remove("test3.txt")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-116-fecc9f240170> in <module>
----> 1 os.remove("test3.txt")
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test3.txt'
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 160/170
8/19/2020 Asif - Jupyter Notebook
In [118]: os.rmdir('folder1/')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-118-e9e89c9edbf0> in <module>
----> 1 os.rmdir('folder1/')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'folder1/'
When the exception occurs Python interpreter stops the current process and passes it to the calling process until it is handled. If exception is
not handled the program will crash.
Exceptions in python can be handled using a try statement. The try block lets you test a block of code for errors.
The block of code which can raise an exception is placed inside the try clause. The code that will handle the exceptions is written in the except
clause.
The finally code block will execute regardless of the result of the try and except blocks.
We can also use the else keyword to define a block of code to be executed if no exceptions were raised.
Python also allows us to create our own exceptions that can be raised from the program using the raise keyword and caught using the except
clause. We can define what kind of error to raise, and the text to print to the user.
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 161/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 162/170
8/19/2020 Asif - Jupyter Notebook
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 163/170
8/19/2020 Asif - Jupyter Notebook
In [130]: try:
print(100/0) # ZeroDivisionError will be encountered here. So the control will pass to except block
except:
print(sys.exc_info()[1] , 'Exception occured') # This statement will be executed
else:
print('No exception occurred') # This will be skipped as code block inside try encountered an exception
finally:
print('Run this block of code always') # This will be always executed
In [134]: try:
print(x) # NameError exception will be encountered as variable x is not defined
except:
print('Variable x is not defined')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 164/170
8/19/2020 Asif - Jupyter Notebook
In [137]: try:
os.remove("test3.txt") # FileNotFoundError will be encountered as "test3.txt" is not present in the directory
else:
print('\nNo exception occurred')
finally:
print('\nRun this block of code always')
except NameError:
print('NameError exception occurred')
except FileNotFoundError:
print('FileNotFoundError exception occurred')
except ZeroDivisionError:
print('ZeroDivisionError exception occurred')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 165/170
8/19/2020 Asif - Jupyter Notebook
except NameError:
print('NameError exception occurred')
except FileNotFoundError:
print('FileNotFoundError exception occurred')
except ZeroDivisionError:
print('ZeroDivisionError exception occurred')
In [144]: try:
x = int(input('Enter first number :- '))
if x > 50:
raise ValueError(x) # If value of x is greater than 50 ValueError exception will be encountered.
except:
print(sys.exc_info()[0])
Built-in Exceptions
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 166/170
8/19/2020 Asif - Jupyter Notebook
In [149]: # OverflowError - This exception is raised when the result of a numeric calculation is too large
try:
import math
print(math.exp(1000))
except OverflowError:
print (sys.exc_info())
else:
print ("Success, no error!")
In [150]: # ZeroDivisionError - This exception is raised when the second operator in a division is zero
try:
x = int(input('Enter first number :- '))
y = int(input('Enter first number :- '))
print(x/y)
except ZeroDivisionError:
print('ZeroDivisionError exception occurred')
In [152]: # NameError - This exception is raised when a variable does not exist
try:
print(x1)
except NameError:
print('NameError exception occurred')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 167/170
8/19/2020 Asif - Jupyter Notebook
try:
a = 50
b = "Asif"
assert a == b
except AssertionError:
print ("Assertion Exception Raised.")
In [157]: # ModuleNotFoundError - This exception is raised when an imported module does not exist
try:
import MyModule
except ModuleNotFoundError:
print ("ModuleNotFoundError Exception Raised.")
In [160]: # KeyError - This exception is raised when key does not exist in a dictionary
try:
mydict = {1:'Asif', 2:'Basit', 3:'Michael'}
print (mydict[4])
except KeyError:
print ("KeyError Exception Raised.")
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 168/170
8/19/2020 Asif - Jupyter Notebook
In [162]: # IndexError - This exception is raised when an index of a sequence does not exist.
try:
mylist = [1,2,3,4,5,6]
print (mylist[10])
except IndexError:
print ("IndexError Exception Raised.")
In [165]: # TypeError - This exception is raised when two different datatypes are combined
try:
a = 50
b = "Asif"
c = a/b
except TypeError:
print ("TypeError Exception Raised.")
In [171]: # AttributeError: - This exception is raised when attribute reference or assignment fails
try:
a = 10
b = a.upper()
print(b)
except AttributeError:
print ("AttributeError Exception Raised.")
In [ ]: try:
x = input('Enter first number :- ')
except:
print('ZeroDivisionError exception occurred')
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 169/170
8/19/2020 Asif - Jupyter Notebook
END
localhost:8888/notebooks/Documents/GitHub/Public/Python/Asif.ipynb 170/170