Python short notes
---------------------
- format string : "".format(<var_name>)
: f"this is a {var_name} "
- int division : a//b
exponent : a**b
- range(<start>, end, <step_size>)
- exceptional handling
try:
<...exception prone code...>
except(<exception_name: ZeroDivisionError, ValueError>):
raise <exception_name>("--msg--")
- function
def my_func(name, citizen='Indian'): #default arguments
pass
def my_func(a, *b): # *args - *b:tuple of args
pass
my_func(1,2,3)
my_func(3,6,8,9,12)
def my_func(a, **b): **kwargs(keyword args) - **b:dict of args
pass
my_func(a=3, d=7,p=3)
my_func(a=3, p=5,s=13,p=3,t=0)
function(a, b, c, *args, d=10, e=34, **kwargs) - order of taking arguments
<func_name> = lambda <arg1>,<arg2> : <expression>
- String
ord("a") : returns the ascii equivalent of a
chr(64) : return equivalent char wrt the int
int -> string = str(num)
str1 = "apple is a purple plant"
----
-> len(str1) #5 --same for list, tuple, set
-> s1 = s[ <start_index> : <end_index> : <step>] #s_rev = str1[::-1] --same in
list also
-> 'p' in str1 #true | 'p' not in str1 #false --same in list also
-> [Link]() | [Link]()
-> [Link]('p')#5 --same in list also
- List
l=[] | l=list() | #list is iterble
l = ['1','2','3']
-> [Link](2) | [Link](<index>, <val>)
-> [Link]() #'3'-['1','2'] | [Link](0) #'1'
-> [Link]() | [Link](reverse = True)
-> shallow copying: l2 = l[:]
-> ['1','2'] + ['3','4'] = ['1','2','3','4']
- Tuple - #immutable
t1 = ('1','2','3') | t1 = '1','2','3' | t1 = '1',
-> sum(t), min(t), max(t)
- Dictionary - key - #immutable
a = {} | a = dict('a'=1, 'b'=2) | a = {'India':'Rupees', 'USA':'Dollar'}
[Link]() | [Link]() #types are 'dict_values', 'dict_keys'
-> for key,val in [Link](): #destructuring dictionary
pass
-> [Link](key) #to get value
- Set
s = {1,2,3,4} | s = {}#wrong
[Link](), [Link]()
- List comprehension
[<kya karna hai?{expression}> for <kiske liye karna hai?{element}> in {kaha
jaakar karna hai?{collection}}]
- OOPS
class ABC:
def __init__(self, var1):
self.var1 = var1
- Dunders or magic methods : to use operator overloading in python
__add__(self,other) : [Link](o2)
__str__(self) : same as toString()
__eq__(self, other) : [Link](o2)