Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Print statement in python :

print("this is %s " %i)


print(“this is %d” %i1 + “%d” %i2)  to print more than two integer
print(f'this is {i}')
print('this is {}'.format(i))

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)]

String is immutable but support replace method  string.replace(oldvalue,


newvalue, count)
List1.sort()  does not return anything, sort that list1 and stored in that list only. So
list1 will be sorted permanently.
Sorted(list1)  it is a function not a method of list. It also sort the list1 and return
that. So the list1 remain unchanged.
Way to check ‘book’ variable if it is present in the list ‘bookself’  when the case of
the input is not fixed.

if book.lower() in (x.lower() for x in bookself):

List unpacking  a,b,*c,d = [1,2,3,4,5,6] a = 1, b=2, c=[3,4,5], d = 6.


Dictionary
Dictionary key must have a property  it must be immutable/ unhashable.
Only string, integer, Boolean,tuple can be key.
Dict1[key]  gives the value for the respective key. But if that key is not
present throws error.
Dict1.get(key)  in this case if the key is not present it returns none datatype.
Dict1.get(key, default_value)  if the key is not present in dictionary, only then
the default value is returned. Otherwise return the value stored in the
dictionary.
Dictionary and set is unordered, so can not grab the item by index.
Methods in set:
Set1.difference(set2)  set1-set2  omit the items from set1 which are present in
set2 and return the rest value. It does not change/update the set1, only told the
difference.
Set1.difference_update(set2)  work same as difference, but update/modify the
set1 permanently. Do not return any value.
Set1.discard(value)  delete the item specified from the set1. Do not return any
value.
Set.intersection()  & operator, set.Union()  | operator.
Ternary operator / IF-Else block in one line:
friend = ['kai','hui']
is_friend = 'kai' in friend
can_message = 'message allowed' if is_friend else 'message not allowed'
print(can_message)

if the name of friend is present in list, value of is_friend will be true, and it will print
“message allowed”.

IS operator vs ==: There's a subtle difference between the Python identity


operator ( is ) and the equality operator ( == ). ... The == operator compares the
value or equality of two objects, whereas the Python is operator checks whether two
variables point to the same memory location.
If two variable contains same values then they are stored in same memory
location. except LIST type object.
x =1
y =1
print(x is y)
print(id(x)) # id function shows the memory address location.
print(id(y))
print(id(1))
print(id(2))

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.

FOR vs WHILE loop:


for item in [1,2,3]:
print(item)

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.

DOC STRING  it contains description about any function


Way to see doc string : help[Function_name] / print(Function_name.__doc__)
Rule to pass value in function 
(Parameter ,*args, default parameter, **kwargs)
Python has strip() , lstrip(), rstrip() function to trim white space .
Normal naming convention in python is SNAKE_CASE, but class naming
convention is CamelCase.

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()

now welcome() is a static metod. @staticmethod is the python decorator that


indicate that the following function / method is a static method.
Class_method vs static_method vs instance_method
Instance vs. Static vs. Class Methods in Python: The Important Differences
(makeuseof.com)

Private, protected and public attribute/method in python:


#syntax
#public = attribute/ method name --> acceable from anywhere of the program
#protected = _attribute/method name --> acceable from only the class it defined and
its derived class
#private = __attribute/method name --> acceable only from the class it defined

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}')

# object._Class.__attribute/method this is the way to make private attribute become


acceable as a public attribute.

MRO  method resolution order:


It’s a depth-first search.
Below two are the way to find mro of a object.
Object/method.__MRO__  this gives tuples in o/p
Object/method.mro()  this gives list o/p
Method Resolution Order (MRO) in Python (srikanthtechnologies.com)

Sorting a list of tuples with respect to the second items in tuples.


my_tuples = [(0,1),(-1,2),(3,-1)]
my_tuples.sort(key = lambda a : a[1])
print(my_tuples)

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}

Higher order Function:


A function that takes another function as parameter or return another function.
Eg- map is a Higher Order Function. It takes another function as an attributes.
Decorator in python:
def dec_func(main_func):

def cover_func( x, **kwargs):

print("**********")
main_func( x, **kwargs)
print("**********")

return cover_func

@dec_func
def greetings( name1, emoji, name2 = 'all' ):
print("hi " + name1 + " and " + name2 +" " + emoji)

greetings('Alo', emoji = ':)' )

**********
hi Alo and all :)
**********

parameter passing rules in python decorators:


emoji is a kwargs for greetings function, so this argument passed after the positional
parameter Alo at the time of greetings function calling.
Now cover function is calling from greetings function
So 1st passed all positional arguments  name1  cover_func will take all these
positional function into *args.
2nd default parameters should be defined in the definition of greetings()  name =
‘all’
But this defaults parameter will act as kwargs for cover_func(), so according to rules
kwargs should be passed at the end.
emoji seems to acts as args in greetings() definition and cover_func() argument
passing. But actually it is a kwarg, so both emoji and name2 will be passed through
**kwargs in cover_func().

If we pass a dictionary as parameter at the time of calling a function, that will


not be kwargs
Eg of python decorator:
# Create an @authenticated decorator that only allows the function to run is user1
has 'valid' set to True:
user1 = {
'name': 'Sorna',
'valid': False
}
user2 = {'name': 'hui',
'valid': True }

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

how to iterate a list without using for loop


l1 = [2,3,4]
x = iter(l1)
while True:
try:
print(next(l1)
except StopIteration:
break

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)

You might also like