Python Fundamentals
Python Fundamentals
Python Fundamentals
Printing
In [ ]: #Basic Printing
#Print String
print("Hello")
print('Hello')
Variable Assignment
In [ ]: var1 = 10
#Multiple variable assignment
a = b = c = d = 10
var2 ,var3 = 20, 30
Escape Char.
In [ ]: #Escape Character
text1 = "Jupyter\tNotebook\nPython\t3\nConda\nAtom"
print(text1)
text2 = "Jupyter\aNotebook\tPython\\3\'Conda\"Atom"
print(text2)
Reserved Keyword
Processing math: 100%
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 1/43
9/21/2019 Python_Fundamentals
Cont. char.
In [ ]: #Continutation Char : continuation character (\)
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
print(a)
b = "Hello" \
" "\
"World"
print(b)
Operators
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 2/43
9/21/2019 Python_Fundamentals
In [ ]: a = 10
b = 5
#Arithmetic Operators
print("="*50)
print("Arithmetic Operator")
print("Sum:",(a + b))
print("Difference:",(a - b))
print("Product:",(a * b))
print("Division:",(a / b))
print("Exponent:",(a ** b))
print("Floor Division:",(a // b))
print("Modulo: ", (a % 3))
#Logical Operators
a = 5
b = 10
c = 5
print("="*50)
print("Logical Operator")
print("AND Operator:")
#And Operator: both need to be true
print(a == c and a != b )
print(b > a and c > b)
print(b ==c and b > a)
print(a == b and c >b)
print("Not Operator:")
print(not(a == c or a != b ) )
print(not(not(a == c or a != b ) ))
Strings
Processing math: 100%
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 3/43
9/21/2019 Python_Fundamentals
In [ ]: #Strings
greet = "Hello"
name = "Jupyter"
print(greet)
print(name)
print(greet + name)
print(greet +' '+ name)
String index,len,in,for,f-string
In [ ]: #String index,len,in,for,f-string
parrot = "Green Bird"
print("Type:",type(parrot))
print("Print Entire String:",parrot)
print("Print first element:",parrot[0])
print("String Slicing")
print(parrot[0:])
print(parrot[:-1])
print(parrot[0:-2])
print(parrot[0::2])
print(parrot[0::3])
print(f"Length of string parrot: {len(parrot)}")
for i in parrot:
print(i)
vow = ''
for i in parrot:
if i in "aeiou":
vow +=i
print(f"Vowels in \'{parrot}\':{vow}")
if "Bird" in parrot:
print(True)
elif "Green" in parrot:
print(True)
if "Blue" in parrot:
print(True)
else:
print(False)
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 4/43
9/21/2019 Python_Fundamentals
For Loop
In [ ]: #For Loop
for i in range(11):
print(i)
string_txt = "1234567890"
print('*'*10)
for i in string_txt:
print(i)
string_txt2 = "Parrot"
print('*'*10)
for i in string_txt2:
print(i)
User Input
In [ ]: #User Input
print("Enter a number:",end ='')
x = input()
print("You typed:",x)
#Multiple input
num1, num2, num3 = input("Enter three numbers: ").split()
if...elif....else
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 5/43
9/21/2019 Python_Fundamentals
In [ ]: #if...elif....else
age = 30
if age >= 25:
print("Age greater than equal to 25 but less than 35.")
elif age >= 35:
print("Age greater than or equal.")
else:
print("Age less than 25")
print("*"*10)
#Nested if
number = 25
if number >= 10:
print("Number greater than 10.")
if number > 15:
print("Number greater than 15.")
if number > 20:
print("Number greater than 20.")
if number == 25:
print(f"Number is {number}.")
else:
print("Number less than 10.")
Strange case
In [ ]: #Strange case:
xt = "False"
if xt:
print("Hello")
Negation
In [ ]: #Negation
print(not True)
print(not False)
In [ ]: '''
#Argument pass and unpack
'''
'''
#Using import module argv
from sys import argv
from sys import argv script, filename1, filename2, filename3, filename4, filename5 = argv
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 7/43
9/21/2019 Python_Fundamentals
In [ ]: #If argv used then replace file1.txt by filename1, file2.txt by filename2 e
#Truncation
txt3 = open('file3.txt','w')
txt3.truncate()
txt3.close()
txt4.close()
txt5.close()
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 8/43
9/21/2019 Python_Fundamentals
#Read char
print("="*40)
print("Using readline(1) to print one char: ")
print(txt1.readline(1))
txt1.close()
More Seek
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 9/43
9/21/2019 Python_Fundamentals
Augmented assigments
In [ ]: var1 = 5
var1 += 5
print(var1)
var1 -= 2
print(var1)
var1 *= 2
print(var1)
var1 /= 2
print(var1)
var1 //= 2
print(var1)
var1 %= 3
print(var1)
str ="Hello"
str +=" "
str +="World"
print(str)
Text Processing
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 10/43
9/21/2019 Python_Fundamentals
In [ ]: #Python treats all uppercase letters to be lower than lowercase letters.
def txt_processor(txt):
#Text Processing
print("="*40)
words = txt.split(' ')
#print(type(words)) #List
def pop_fn(txt,num):
print(txt.pop(num))
#Function call:
print("Python treats all uppercase letters to be lower than lowercase lette
print("Text with Lower and Upper Case Words:")
Text1 = "Comments are very important while writing a program"
txt_processor(Text1)
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 11/43
9/21/2019 Python_Fundamentals
pop_fn(words3,-2)
print("Print Last Word",end=' ')
pop_fn(words3,-1)
While Loop
In [ ]: i = 0
while i < 6:
print(i)
i +=1
for i in range(var1):
if i == 3:
break
print(i)
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 12/43
9/21/2019 Python_Fundamentals
print("\n")
print("=" * 40)
print("\n")
num1 = int(input("Enter a number between 10 and 15>>"))
while num1 >= 10:
print(f"Number is {num1}")
num1 -= 1
else:
print("Number is less than 10")
Function
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 13/43
9/21/2019 Python_Fundamentals
def fun2(a,b):
print("\nFunction with Arguments")
print(f"First argument is {a}")
print(f"Second arument is {b}")
def funrtr(a,b):
print("This function returns value",end =' ')
return a + b
def calculator(a,b):
print("Sum:",(a + b))
print("Difference:",(a - b))
print("Product:",(a * b))
print("Division:",(a / b))
print("Floor Division:",(a // b))
print("Exponent:",(a**b))
#Function call:
fun1()
fun2(10,20)
print("\n")
var1 = funrtr(10,20)
print(var1)
print("\n")
print("*"*40)
calculator(40,20)
Lists
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 14/43
9/21/2019 Python_Fundamentals
#Append to List
#Append add to end of List
fruits.append('Orange')
print(f"\nUpdate List fruits :{fruits}")
for i in range(len(fruits)):
if fruits[i] == 'Kiwi':
print("Kiwi in List fruits.")
break
else:
print("No Kiwi in List fruits.")
#Empty List
empty_l = []
print(empty_l)
#List comprehension
list_comp = [2 ** x for x in range(10)]
print(list_comp)
#Equivalent to
'''pow2 = []
for x in range(10):
pow2.append(2 ** x)'''
#Insert
#Insert doesnot replace but add at specific index
fruits.insert(3,'Kiwi')
Processing math: 100%
print("\nAdding Kiwi in List")
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 15/43
9/21/2019 Python_Fundamentals
print(f"Update List fruits :{fruits}")
print("=" * 50)
print("List in List")
even = [0,2,4,6,8]
print(f"List 1 of Even numbers :{even}")
odd = [1,3,5,7,9]
print(f"List 2 of Odd numbers :{odd}")
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 16/43
9/21/2019 Python_Fundamentals
#List Extension
list_a = list(range(10))
list_b = list(range(10,20))
list_a.extend(list_b)
print(f"Extended List:{list_a}")
#List Copy
list_c = [4,5,6,7]
print(f"\nOrignal List : {list_c}")
list_c_copy = list_c
print(f"Copied list by using assigment operator: {list_c_copy}")
list_c_copy.append(11)
print("="*50)
print(f"Copied List after appending data: {list_c_copy}")
print(f"Orignal List: {list_c}")
print("Both are the same. The orignal lsit has been changed.")
print("\n")
print("="*50)
print("Now using copy() method:")
list_d = [9,10,11,12]
print(f"Orignal List:{list_d}")
list_d_copy = list_d.copy()
print(f"Copied list by using copy function: {list_d_copy}")
list_d_copy.append(23)
print("="*50)
print(f"Copied List after appending data: {list_d_copy}")
print(f"Orignal List: {list_d}")
print("Orignal List Unchnaged.")
#List Reversal
print("="*50)
list_e = [12, 78,0,56,89,98,11,6,4,7]
print(f"New List:{list_e}")
list_e.reverse()
print(f"Reverse List:{list_e}")
list_e.sort()
print(f"Sorted List:{list_e}")
Tuples
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 17/43
9/21/2019 Python_Fundamentals
In [ ]: #Tuples
#Tuples are immutable
tup = ("a","b","c")
print(f"Tuple:{tup}")
print("\nPrint Individual Tuple Element:")
for i in tup:
print(i)
print("="*50)
print("New Tuple:")
welcome = "Welcome to the Train","John","2019"
print(welcome)
print("\nFirst element:")
print(welcome[0])
print("\nUpdated Tuples:")
print(welcome)
print("="*50)
print('''Advantages of Tuple over List
Since, tuples are quite similiar to lists, both of them are used in similar
However, there are certain advantages of implementing a tuple over a list.
Below listed are some of the main advantages:
\t1)We generally use tuple for heterogeneous (different) datatypes and list
\t2)Since tuple are immutable, iterating through tuple is faster than with
\t boost.
\t3)Tuples that contain immutable elements can be used as key for a diction
\t4)If you have data that doesn't change, implementing it as tuple will gua
print("="*50)
print("Tuple Un-pack")
#Tuple element Un-packing
Song = 'Stairways to Heaven','Led Zepplin',1971
track,artist,year = Song
print(f"Tuple Song:{Song}")
print(f"Track:{track}")
print(f"Artist:{artist}")
print(f"Year:{year}")
print("="*50)
print("Tuple in Tuple")
Sng = ("Rock", "1970s",(("Stairways to Heaven","Led Zepplin"),("Hey Jude","
print(f"Tuple for Rock Song :\n{Sng}")
genre,era,trk_n_artist = Sng
len_t = len("Stairways to Heaven")
print(f"Genre: {genre}")
print(f"Era:{era}")
print(f"Tracks and Artitst:{trk_n_artist}")
cnt = 1
for i in trk_n_artist:
Processing math: 100% print(f"Record {cnt}:")
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 18/43
9/21/2019 Python_Fundamentals
print(f"{i[0]}\n -- {i[1]}")
cnt +=1
print("="*50)
Sng_lst= ("Rock", "1970s",["Stairways to Heaven","Led Zepplin"])
print(f"List in Tuple :\n{Sng_lst}")
genre_2,era_2,trk_n_artist_2 = Sng_lst
print(f"Genre: {genre_2}")
print(f"Era:{era_2}")
print(f"Tracks and Artitst:{trk_n_artist_2}")
trk_n_artist_2.append("Hey Jude")
trk_n_artist_2.append("Beatles")
trk_n_artist_2.append("We Will Rock You")
trk_n_artist_2.append("Queen")
print(f"\nList in Tuple (updated) :\n{Sng_lst}")
'''we cannot change the elements in a tuple. That also means we cannot dele
But deleting a tuple entirely is possible using the keyword del.
del Sng_lst
'''
print("="*50)
print(f"Index of Rock : {Sng_lst.index ('Rock')}")
print(f"Index of 1970s: {Sng_lst.index ('1970s')}")
Ranges
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 19/43
9/21/2019 Python_Fundamentals
In [ ]: print(range(100))
my_List = list(range(100))
print(f"List of range 100 : {my_List}")
even = list(range(0,10,2))
print(f"List of even numbers : {even}")
odd = list(range(1,10,2))
print(f"List of odd numbers : {odd}")
#Index
print("\n")
num = range(0,10)
print(num)
print(num[0])
print(num[2])
print(num.index(9))
print("\n")
string1 = "Hello"
print(string1)
print(string1[0])
print(string1[2])
print(string1.index('l'))
#Negative Slicing
print("\nList details:")
for i in num:
print(i)
print("\nNegative Slicing")
#Negative Slicing when used implicitly reverses the index
for i in num[::-2]:
print(i)
print("\n")
for i in num[10:0:-2]:
print(i)
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 20/43
9/21/2019 Python_Fundamentals
O_range = range(0,100,4)
P_range = O_range[::5]
print("\n")
print("Number List:")
for i in O_range:
print(i)
print("\n")
print("Sliced List every 5 slice:")
for i in P_range:
print(i)
Enumerate
The enumerate() method adds counter to an iterable and returns it (the enumerate object). The
syntax of enumerate() is:
enumerate(iterable, start=0)
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 21/43
9/21/2019 Python_Fundamentals
print(type(enumerateGrocery))
# converting to list
print(list(enumerateGrocery))
all() function
The all() method returns True when all elements in the given iterable are true. If not, it returns False.
The all() method returns: True - If all elements in an iterable are true False - If any element in an
iterable is false
# empty iterable
l = []
print(all(l))
any() function
any() returns:
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 22/43
9/21/2019 Python_Fundamentals
In [ ]: l = [1, 3, 4, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
Dictonary
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 23/43
9/21/2019 Python_Fundamentals
In [ ]: #Dictionary
# variable = {key:value, key: value,key: value}
#Values mutable but keys are immutable
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
fruits = {'OR':'Orange',
'PR':'Pear',
'AP':'Apple'}
print(fruits)
for i in fruits:
print(f"{i}:{fruits[i]}")
key_tup = ('OR','PR','AP')
for i in key_tup:
print(fruits[i])
del fruits
try:
print(fruits)
except:
print("Dictionary Deleted.")
print("="*50)
#Re-assign tuples
key_tup = ('OR','PR','AP','GR')
print(key_tup)
val_list = ['Orange','Pear','Apple','Grapes']
print(key_tup)
fruits = dict({key_tup:val_list})
print("Bad way of using tuples and list in dictonary")
print(fruits)
Processing math: 100%
del fruits
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 24/43
9/21/2019 Python_Fundamentals
'''Above is bad way of using tuples and list in dictonary'''
print("="*50)
key_tup = ('OR','PR','AP','GR')
print(key_tup)
val_list = ['Orange','Pear','Apple','Grapes']
print(val_list)
print("Good way of using tuples and list in dictonary")
fruits = {key_tup[0]:val_list[0],key_tup[1]:val_list[1],key_tup[2]:val_list
print(fruits)
'''
Individual element key and value deletion in dictionary
del fruits['GR']
print(fruits)
'''
print("="*50)
print(fruits.items())
print("Using loop and multiple variable assignment to print individual item
for i,j in list(fruits.items()):
print(f"Key is {i} and Value is {j}")
print("="*50)
print("Searching the dictionary and retreiving value using get() function."
val1 = fruits.get('GR')
print(val1)
'''
Python 2
print("="*50)
val2 = fruits.has_key('Orange')
print(val2)
'''
print("="*50)
fruits.clear()
print("Clearing dictonary fruits")
print("Empty dictonary fruits:")
print(fruits)
print("="*50)
print("Dictionary Creation using update() function.")
fruits = {'OR':'Orange',
'PR':'Pear',
'AP':'Apple'}
veg = {'TM':'Tomato',
'SP':'Spinach',
'PO':'Potato'}
market ={}
market.update(fruits)
print(market)
market.update(veg)
print(market)
market_2 = market.copy()
print(market_2)
Processing math: 100%
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 25/43
9/21/2019 Python_Fundamentals
Set
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 26/43
9/21/2019 Python_Fundamentals
fruits.add("Grape")
veg.add("Celery")
print(fruits)
print(veg)
'''
print(set_rng)
print(set_tup)
print(set_lst
'''
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
#set_new[0]
#TypeError: 'set' object does not support indexing
'''
A set is an unordered collection of items. Every element is unique (no dupl
However, the set itself is mutable. We can add or remove items from it.Sets
mathematical set operations like union, intersection, symmetric difference
'''
Processing math: 100%
#Add to set similar to append in list
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 27/43
9/21/2019 Python_Fundamentals
set_new.add(12)
print(set_new)
print(set_new)
#o/p:{2, 4, 7, 9, 10, 12, 20, 21, 22, 25, 27, 28}
#Clear a set
set_new.clear()
print(set_new)
#o/p: set()
'''
even = set(range(0,40,2))
even_2 = set(range(0,10,2))
odd = set(range(1,40,2))
#UNION
union_set = even.union(odd)
print(union_set)
#union_set2 = even|odd
#print(union_set2)
#INTERSECTION
#inter_set = even.intersection(odd)
inter_set = even.intersection(even_2)
print(inter_set)
#DIFFERENCE
Difference of A and B (A - B) is a set of elements that are only in A but n
Processing math: 100%
Similarly, B - A is a set of element in B but not in A.
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 28/43
9/21/2019 Python_Fundamentals
diff_set = even.difference(even_2)
#diff_set = even - even_2
print(diff_set)
#SYMMETRIC DIFFERENCE
#Symmetric Difference of A and B is a set of elements in both A and B excep
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
sym_diff = A ^ B
'''
#SET OPERATIONS:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("=" * 50)
print("Set Operations:")
print(f"Set A : {A}")
print(f"Set B : {B}")
#Union : A | B
#Set of all elements of A and B but will not have duplicates as it is a set
print(f"Union: {A.union(B)}")
#Intersection : A & B
#Set of whats common in both
print(f"Intersection: {A.intersection(B)}")
#Difference : A - B
#Set of whats unique in A
print(f"Difference :{A.difference(B)}")
#Symmetric Difference : A ^ B
#Set of whats not comman in both
print(f"Symmetric Difference : {A.symmetric_difference(B)}")
print("=" * 50)
print("Sets:")
print(f"Set A : {A}")
print(f"Set B : {B}")
print("Performing Difference Update")
A.difference_update(B)
print("Sets after difference update:")
print(f"Set A : {A}")
print(f"Set B : {B}")
print('''Why ?
The difference_update() updates set A with the set difference of A-B.
A will be equal to A-B
B will be unchanged
''')
a = {1,2}
b = {1,2,3,4}
print(a.issubset(b))
print(a.issuperset(b))
Processing math: 100%
print(b.issuperset(a))
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 29/43
9/21/2019 Python_Fundamentals
#Disjoint
#No common element
print("=" * 50)
c = {3,4,5}
print(a.isdisjoint(c))
#Frozen Set
abc =frozenset(range(0,100,2))
#abc.add(3)
#abc.remove(2)
#abc.discard(4)
#abc.difference_update(b)
#add,remove,discard,difference_update will cause errors
#union, intersetion, difference is allowed
One of the popular approach to solve a programming problem is by creating objects. This is known
as Object-Oriented Programming (OOP).
Important concepts:
Inheritance: A process of using details from a new class without modifying existing class
Polymorphism A concept of using common operation in different ways for different data input.
Constructors in Python
Class functions that begins with double underscore (__) are called special functions as they have
special meaning.
Of one particular interest is the init() function. This special function gets called whenever a new
object of that class is instantiated.
This type of function is also called constructors in Object Oriented Programming (OOP). We
normally use it to initialize all the variables.
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 30/43
9/21/2019 Python_Fundamentals
def __init__(self,make,price):
self.make = make
self.price = price
self.on = False
def switch_on(self):
self.on = True
print("Kettle Details:")
print("="*50)
print(f"Make: {Kenwood.make}")
print(f"Price: ${Kenwood.price}")
print(f"Switch Status: {Kenwood.on}")
print("\n")
print(f"Make: {Hamilton.make}")
print(f"Price: ${Hamilton.price}")
print(f"Switch Status: {Hamilton.on}")
print("="*50)
#Delete attribute
'''
del Kenwood.make
print(f"Make: {Kenwood.make}")
'''
Bosch = Kettle("Bosch",19.05)
print("New Kettle Details:")
print(f"Make: {Bosch.make}")
print(f"Price: ${Bosch.price}")
print(f"Switch Status: {Bosch.on}")
#Delete Object
'''
del Bosch
print(f"Make: {Bosch.make}")
print(f"Price: ${Bosch.price}")
print(f"Switch Status: {Bosch.on}")
On the command del Bosch, this binding is removed and the name Bosch is del
The object however continues to exist in memory and if no other name is bou
This automatic destruction of unreferenced objects in Python is also called
'''
#Calling Methods:
#USING Objects to call methods
Kenwood.switch_on()
Hamilton.switch_on()
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 31/43
9/21/2019 Python_Fundamentals
print("="*50)
print("Updated Switch Status:")
print(f"Make: {Kenwood.make}")
print(f"Price: ${Kenwood.price}")
print(f"Switch Status: {Kenwood.on}")
print("\n")
print(f"Make: {Hamilton.make}")
print(f"Price: ${Hamilton.price}")
print(f"Switch Status: {Hamilton.on}")
print("\n")
print(f"Make: {Bosch.make}")
print(f"Price: ${Bosch.price}")
print(f"Switch Status: {Bosch.on}")
print("="*50)
#Attribute Sharing:
print("="*50)
print(Kettle.power_source)
print(Kenwood.power_source)
print(Hamilton.power_source)
print(Bosch.power_source)
print("="*50)
print(Kettle.__dict__)
print(Kenwood.__dict__)
print(Hamilton.__dict__)
print(Bosch.__dict__)
print('''Only Kettle has attribute power_source and none of the objects hav
Inheritance
Processing math: 100%
In [ ]:
Multiple Inheritance
Operator Overloading
In [ ]:
We use lambda functions when we require a nameless function for a short period of time.
Filter Function
The function is called with all the items in the list and a new list is returned which contains items for
which the function evaluats to True. Checks condition and return value for true case>
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 33/43
9/21/2019 Python_Fundamentals
The function is called with all the items in the list and a new list is returned which contains items
returned by that function for each item. Basically Evaluates and return the output.
Generators
In [ ]:
print(datetime_object)
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 34/43
9/21/2019 Python_Fundamentals
print(date_object)
Create date objects from a timestamp. A Unix timestamp is the number of seconds between a
particular date and January 1, 1970 (Unix Epoc) at UTC.
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 35/43
9/21/2019 Python_Fundamentals
datetime.timedelta
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 36/43
9/21/2019 Python_Fundamentals
t1 = timedelta(seconds = 33)
t2 = timedelta(seconds = 54)
t3 = t1 - t2
datetime to string
The way date and time is represented may be different in different places, organizations etc.
It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.
The strftime() method is defined under classes date, datetime and time.
The method creates a formatted string from a given date, datetime or time object.
The strftime() method takes one or more format codes and returns a formatted string based on it.
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 37/43
9/21/2019 Python_Fundamentals
t = now.strftime("%H:%M:%S")
print("time:", t)
s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)
s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)
The strptime() method creates a datetime object from a given string (representing date and time)
sleep() Function
The sleep() function suspends execution of the current thread for a given number of seconds.
print("Printed immediately.")
time.sleep(2.4)
print("Printed after 2.4 seconds.")
A thread is a subset of the process. A process can have one or more threads.
The sleep() function suspends execution of the current thread for a given number of seconds.
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 38/43
9/21/2019 Python_Fundamentals
def print_hello_three_times():
for i in range(3):
print("Hello")
def print_hi_three_times():
for i in range(3):
print("Hi")
t1 = threading.Thread(target=print_hello_three_times)
t2 = threading.Thread(target=print_hi_three_times)
t1.start()
t2.start()
def print_hello():
for i in range(4):
#time.sleep(0.5)
print("Hello")
def print_hi():
for i in range(4):
time.sleep(0.7)
print("Hi")
t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_hi)
t1.start()
t2.start()
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 39/43
9/21/2019 Python_Fundamentals
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
scope_test()
print("In global scope:", spam)
In [ ]:
Try,Except
In [ ]: try :
print(a)
except:
print("Error.Undefined var")
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 40/43
9/21/2019 Python_Fundamentals
In [ ]: '''
Custom Module
===============
#Example_mod.py
def fun1(a,b):
print("Sum = {a+b}")
================
#Main.py
import example_mod
example_mod.fun1(10,20)
'''
stuff()
def addv(a,b):
add1 = a + b
return a
x = addv(2,7)
print(x)
hr = int(input("Enter Hours:"))
rt = float(input("Enter rate per hour:"))
pay = computepay1(hr,rt)
print("Pay:",pay)
In [ ]: n = 0
while n > 0:
print("Test")
Regular Expression
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 41/43
9/21/2019 Python_Fundamentals
In [ ]:
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 42/43
9/21/2019 Python_Fundamentals
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 43/43