Python
Python
Python
Special _string - written within three single quotes. We can write a string for more
than one line long.
Escape sequence \ this back slash indicates that whatever comes after this is a
string.
To print integer with sign
print(“this is %+d” %i1 + “%+d” %i2) this print integer with sign
print(f”hi {i:+}”)
print(“hi {0:+}”.format(i))
LIST
List1 = [1,2,’alo’]
List2 = list1[:] copying list1 into list2. Different memory will be allocated for two list.
List2 = list1 we are assigning same memory address to two lists. So change of
item in one list will also change in other list.
List methods
List2 = list1.copy() copy list1 to list2. Same as list1[:]
List1.append(object) add / append only one object at the end of the list.
List1.extend(obj1) add/ append objects at the end of the list but it takes
only one iterable object as input
List1.insert(index, obj ) insert only one object at the index place.
List1.pop(index) pop out the item at the index place. If no index place is given pop
out from the end of the list. Pop method return the item that is popped out from the
list. Z = list1.pop() return a value.
List1.remove(index) same as pop method but always an index is needed. But
does not return a value. Z = list1.remove() does not return anything.
List1.clear() delete all items from the list.
List1.index(value, start, stop) find the index of 1st occurrence of value given within
start and stop range. this method throws value error if the value is not present in
list
We can check earlier if that item is present in list by “print(value in list)” it will
return True if present.
String.find(value, start, stop) and list.index(value, start, stop) gives same o/p
Also string.index() method available.
String.rfind(), string.rindex() gives the index of last matches inside the string.
Above methods are applicable to find both character and substring inside a
string
x = [i for i,j in enumerate(word1) if j == 'strfind']
this is only applicable to find character but is gives index of all occurrence.
But the below method give all the occurrence of a substring in a string
x = [i for i in range(len(word1)) if word1.startswith(strfind,i)]
if book.lower() in (x.lower() for x in bookself):
if the name of friend is present in list, value of is_friend will be true, and it will print
“message allowed”.
print([1,2] is [1,2])
print(1 is 1.0)
Above 2 also gives False.
Int and floats are 2 different data types so stored in different memory location.
Every times a list created, a different memory location will allocate for that list,
so two identical list can also be stored in different memory location.
String can have negative indexing, but in range operator it does not contain negative
indexing. To do the negative looping in range operator range(10,0,-1). It don’t take
range(0,10,-1).
Enumerate() : this function give the index of all the item/letter of the variable passed
through it. It takes list, tuples, set, string as input variable.
i=0
while i < len([1,2,3]):
print([1,2,3][i])
i = i+1
For loop can never go for infinite loop, but while loop can be.to check a condition(like
< or > ) we have to use while loop
Print(function_name) show the memory location of the function stored.
Function parameters vs Arguments variable that are used to pass the value at
the function definition are call Parameters.
Actual value of those variables that are passed at the time of Function calling are
called Arguments.
Default Parameter If we set some values to the Parameters at the time of
defining the function. This is called default parameters. So If that function is called
with-out any Argument passing, then the Function will take the Default parameter
and execute.
INHERITANCE : child class can access attribute and method of parent class, but
parent class can not access from child class.
In POLYMORPHISM, if both parent class and child class contains a method defined
with same name, child class method will overwrite the parent class method.
All method of a class must have self parameter by default, this self parameter
contains object that is instantiated. This type of method is called instance method.
class Emp():
def empdetails(self):
self.name = "Don"
return self.name
def welcome(self):
print("hi!")
emp1 = Emp()
print(emp1.empdetails())
emp1.welcome()
Static method method that has no need the self parameter / object to be passes.
class Emp():
def empdetails(self):
self.name = "Don"
return self.name
@staticmethod
def welcome():
print("hi!")
emp1 = Emp()
print(emp1.empdetails())
emp1.welcome()
class Car:
numberofwheels = 4
_colour = "black"
__maunfactringyear = 2020
class Bmw(Car):
def __init__(self):
print(f'protected attribute colour : {self._colour}' )
car1 = Car()
print("public attribute numberofwheels: {} " .format(car1.numberofwheels))
bmw = Bmw()
print(f'private attribute maunfactringyear :{car1._Car__maunfactringyear}')
list comprehension:
my_list = [num**2 for num in range (100) if num %2 == 0]
print(my_list)
it takes the number in the range 0 to 100, check if the number is even then return the
square of that number.
Dictionary comprehension:
my_strings = ['a', 'b', 'c', 'd', 'e']
my_numbers = [5,4,3,2,1]
my_dict = {key:value*2 for key,value in zip(my_strings,my_numbers) if value %2 ==
0}
print(my_dict)
{'b': 4, 'd': 8}
print("**********")
main_func( x, **kwargs)
print("**********")
return cover_func
@dec_func
def greetings( name1, emoji, name2 = 'all' ):
print("hi " + name1 + " and " + name2 +" " + emoji)
**********
hi Alo and all :)
**********
def authenticated(fn):
# code here
def cover(*args):
for i in args:
if i['valid']:
fn(i)
return cover
@authenticated
def message_friends(user):
print('message has been sent to {}'.format (user['name']))
#print('message has been sent')
message_friends(user1, user2)
following dunder method must be defined in a class to make it’s object iterable
def __iter__(self):
return self
for the excecption handling used in the code it will not give any
error(IndexError: list index out of range)
Exception handling in python using custom exception class:
class MinimumDepositError(Exception):
pass
class MinimumBalanceError(Exception):
def __init__(self,st):
self.st = st
def do_diposit(b,a):
if a < 2000:
raise MinimumDepositError('The Minimum amount of Deposit should be
2000.')
else:
print('Updated Balance Amount: {}'.format(b+a))
def do_withdrawal(b,a):
if b-a < 500:
raise MinimumBalanceError('You cannot withdraw this amount due to
Minimum Balance Policy')
else:
print('Updated Balance Amount: {}'.format(b-a))
def Bank_ATM(balance,choice,amount):
if balance < 500:
raise ValueError("As per the Minimum Balance Policy, Balance must be
at least 500")
elif choice == 1:
do_diposit(balance,amount)
elif choice == 2:
do_withdrawal(balance,amount)
if __name__ == '__main__':
bal = int(input())
ch = int(input())
amt = int(input())
try:
Bank_ATM(bal,ch,amt)
except ValueError as e:
print(e)
except MinimumDepositError as e:
print(e)
except MinimumBalanceError as e:
print(e)
reg ex:
regex used to find the match of a string inside of another string.
Re.<method>(string for which match will be find, string in which match will be
find)
Regex module has following methods
Re.start starting index/position of the match
Re.end
Re.span
Re.search return
Re.match match the string but the string should the present from the starting of
the target string
Re.fullmatch both string should be same
Re.findall return all the existence of matching word in target
Module/package:
From <module> import <function> if we only need 1 function from that module.
From <package>.<package>.<module> import <function>
From <package>.<package> import <module> in this case we have to use
function as below <module>.<function>
Dir(<module>) gives all the method/function available in this module
Defaultdict module:
from collections import defaultdict
d = defaultdict(lambda:5,{'a':3,'b':5})
print(d['c'])
now as the key(‘c’) is not present in the dictionary so it will return the value that is
against lambda. But for normal dictionary in this scenario it gives error.
So what value will be present against key(lambda) will be the default value.
Datetime module:
def dateandtime(val,tup):
import datetime
li1 = []
if val == 1:
x = datetime.date(tup[0],tup[1],tup[2])
li1.append(x)
li1.append(x.strftime("%d/%m/%Y"))
elif val == 2:
from datetime import datetime
x = (datetime.fromtimestamp(tup[0])).date()
li1.append(x)
elif val == 3:
x = datetime.time(tup[0],tup[1],tup[2])
li1.append(x)
li1.append(x.strftime('%I'))
elif val==4:
x = datetime.date(tup[0],tup[1],tup[2])
li1.append(x.strftime('%A'))
li1.append(x.strftime('%B'))
li1.append(x.strftime('%j'))
elif val == 5:
x = datetime.datetime(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5])
li1.append(x)
return li1
Cryptography.fernet module:
from cryptography.fernet import Fernet
def encrdecr(keyval, textencr, textdecr):
# Write your code here
main = []
#key = Fernet.generate_key() --> this is used to generate a new key
k = Fernet(keyval)
t = k.encrypt(textencr)
b = str(k.decrypt(textdecr),'utf-8') used to remove the ‘b’ from prefix
main.append(t)
main.append(b)
return(main)