Posts

Showing posts with the label PYTHON ADVANCED

PYTHON ADVANCED - 19 : CONTEXT MANAGERS

 LAST TOPIC OF PYTHON COURSE, HERE SHORT DESCRIPTION OF CONTEXT MANAGERS with open ( 'notes.txt' , 'w' ) as file :     file . write ( 'some todoo......' )

PYTHON ADVANCED - 18: SHALLOW VS DEEP COPYING

 IN THIS TUTORIAL,  YOU WILL LEARN ABOUT SHALLOW VS DEEP COPYING. NOTE: TRY ALL CODES ( WHICH ARE COMMENTED OUT GREEN LINES) # org = 5 # cpy = org # cpy = 6 # print(cpy) # print(org) import copy org = [ 0 , 1 , 2 , 3 , 4 ] # cpy = org    #--> deep copy # cpy = copy.copy(org)    #--> swallow copy (original wont get affected) # cpy = org.copy() # cpy = list(org) cpy = org [:] cpy [ 0 ] = - 10 print ( cpy ) print ( org )

PYTHON ADVANCED - 17 : ASTERISK

 HERE, YOU WILL LEARN ABOUT ASTERISK IN PYTHON NOTE: TRY ALL TYPES OF CODES WHICH ARE COMMENTED OUT(GREEN LINES) # * * * * * * * * * * * * * * * * # result = 2**4 # print(result) # zeros = "AB"*10 #(0,1)*10 #[0,1]*10 # print(zeros) # def foo(a, b, *args, **kwargs): #     print(a) #     for arg in args: #         print(arg) #     for key in kwargs: #         print(key, kwargs[key]) # foo(1,2,3,4,5, six = 6, seven =7) # def foo(a,b, *, c): #     print(a,b,c) # foo(1,2,c=3)     # def foo(a,b,c): #     print(a,b,c) # mylist = [0,1,2] # foo(*mylist) # def foo(a,b,c): #     print(a,b,c) # dict = {"a" :0, "b" :1, "c" :2} # foo(**dict) # nmbrs = [1,2,3,4,5,6] # # *beginning, last = nmbrs # # beginning, *last = nmbrs # print(beginning) # print(last) # tuple = (1,2,3) # list = [4,5,6] # nlist = [*tuple, *list] # print(nlist) # tuple = (1,2,3) # set = {4,5,6} # nset = [*tuple, *set] #...

PYTHON ADVANCED - 16 : FUNCTIONS ARGUMENTS

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT FUNCTIONS ARGUMENTS NOTE: TRY ALL METHODS/ CODES WHICH ARE COMMENTED OUT # def print_name(name): #     print(name) # print_name('Shayan') # def foo(a,b,c,d =4): #     print(a,b,c,d) # foo(a=1,b=2,c=3)   --> d will be printed too. # foo(c=1,b=2,a=3)    --> keywords matter not the position # def foo(a,b,c): #     print(a,b,c) # dict = {"a":1, "b":2, "c":3} # foo(**dict)     # def foo(): #     global number #     x = number #     number= 3 #     print('number inside function:',x) # number  = 0 # foo()     # print(number) # def foo(x): #     x = 5 # var = 10 # foo(var) # print(var)     def foo ( list ):     list .append( 4 )     list [ 0 ] = 400 List = [ 1 , 2 , 3 ] foo ( List ) print ( List )    

PYTHON ADVANCED - 15 : MULTIPROCESSING VS THREADING

 ONE OF MY FAVOURITE TOPIC WHICH YOU GONNA LEARN TODAY IS MUTLIPROCESSING VS THREADING. # THREADING VS MULTIPROCESSING #GIL : global interpreter lock from multiprocessing import process import os import time def square_nmbrs ():     for i in range ( 100 ):         i * i         time . sleep ( 0.1 ) processes = [] num_processes = os . cpu_count () # create processes for i in range ( num_processes ):     p = process ( target = square_nmbrs )     processes . append ( p ) #start for p in processes :     p .start() #join for p in processes :     p .join() print ( 'end main' ) from threading import Thread  

PYTHON ADVANCED - 14: GENERATORS

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT GENERATORS: NOTE: TRY ALL METHODS WHICH ARE COMMENTED OUT # def mygenerator(): #     yield 3 #     yield 2 #     yield 1 # g = mygenerator() # for i in g: #     print(i) # print(sum(g)) # print(sorted(g)) # value = next(g) # print(value) # value = next(g) # print(value) # value = next(g) # print(value) # value = next(g) # print(value) # def countdown(num): #     print("Starting") #     while num > 0 : #         yield num #         num -=1 # cd = countdown(4) # value = next(cd)         # print(value) # print(next(cd)) # print(next(cd)) # print(next(cd)) import sys # def firstn(n): #     nums = [1] #     num = 0 #     while num < n: #         nums.append(num) #         num +=1 #     return  nums # def firstn_generator(n): #   ...

PYTHON ADVANCED - 13: DECORATORS

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT DECORATORS. # @mydecorator def dosomething ():     pass def start_end_decorator ( func ):     def wrapper ():         print ( 'Start' )         func ()         print ( 'End' )     return wrapper     def print_name ():     print ( 'Alex' ) print_name = start_end_decorator ( print_name ) print_name ()

PYTHON ADVANCED - 12 : RANDOM NUMBERS

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT RANDOM NUMBERS. TRY OUT ALL METHODS/CODES. import random # a = random.uniform(1, 10) # a = random.randint(1, 10) # a = random.randrange(1, 10) # a = random.normalvariate(1, 10) # print(a) # myList = list("ABCDEFGH") # print(myList) # a = random.choices(myList) # a = random.sample(myList, 4) # random.shuffle(myList) # random.seed(2) # print(random.random()) # print(random.randint(1,10)) # print(myList) import secrets # list = list("ABCDEFGH") # # a = secrets.randbelow(10) # # a = secrets.randbits(10) # a = secrets.choice(list) # print(a)

PYTHON ADVANCED - 11 : JSON TUTORIAL

 IN THIS TUTORIAL,  YOU WILL LEARN ABOUT JSON TUTORIAL: NOTE: TRY ALL TYPES OF CODE WHICH ARE COMMENTED OUT. import json #converting python file to json(javascript oriented programming) # person = {"name":"Shayan", "age": 30, "city": "Patna", "hasChildren": False, "titles": ["Engineer", "Programmer"]} # personJSON = json.dumps(person, indent=4)#, sort_keys=True) # print(personJSON) # with open('person.json', 'w') as file:       #--> file in json #     json.dump(person, file, indent=4) #converting json to python file # person = json.loads(personJSON) # print(person) # with open('person.json', 'r') as file:         #--> file reading in python #     person = json.load(file) #     print(person) class User :     def __init__ ( self , name , age ):         self . name = name         self . age = age user = User ( 'Shayan' , 16 ) def encode_user ( o ):...

PYTHON ADVANCED - 10 : LOGGING

 IN THIS TUTORIAL, WE WILL LEARN ABOUT LOGGING IN PYTHON: import logging logging . basicConfig ( level = logging . DEBUG , format = ' %(asctime)s - %(name)s - %(levelname)s - %(message)s ' ,                     datefmt = '%m/ %d /%Y %H:%M:%S' ) import helper                     # logging.debug("This is a debug message") # logging.info("This is a info message") # logging.warning("This is a warning message") # logging.error("This is a error message") # logging.critical("This is a critical message")

PYTHON ADVANCED - 09: EXCEPTIONS

 IN THIS TUTORIAL, WE WILL LEARN ABOUT EXCEPTIONS: NOTE: TRY ALL METHODS/CODES. # ERRORS and Exceptions # x = -5 # if x<0: #     raise Exception('x shuld be positive') # assert (x >= 0), "x is not positive" # try:     # a = 5/0 # except: #     print("Galti se error")     # except Exception as e: #     print(e) # except ZeroDivisionError: #     print() class ValueTooHighError ( Exception ):     pass class ValueTooSmallError ( Exception ):     def __init__ ( self , message , value ):         self . message = message         self . value = value def test_value ( x ):     if x > 100 :         raise ValueTooHighError ( " value is too high" )     if x > 5 :         raise ValueTooSmallError ( "Value is too small" )   try :     test_value ( 1 ) except ValueTooHighError as e...

PYTHON ADVANCED - 08: LAMBDA

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT LAMBDA: NOTE: TRY ALL METHODS/ CODES' #lambda arguments : expressions # add10 = lambda x: x +10 # print(add10(5)) # def add10_func(x): #     return x + 10 # mult = lambda x,y: x*y # print(mult(2,7))     # points2D = [(1,2), (3,4), (5,6), (-1,3)] # # points2D_sorted = sorted(points2D) # # points2D_sorted = sorted(points2D, key=lambda x: x[1])  #--> sorts by Y coordinate value # points2D_sorted = sorted(points2D, key=lambda x: x[0] + x[1]) # print(points2D) # print(points2D_sorted) #map(func,seq) # a =[1,2,3,4,5,6] # b = map(lambda x: x*2, a) # print(list(b)) # c = [x*2 for x in a] # print(c) # filter(func,seq)  --> prints only even function # a =[1,2,3,4,5,6] # b = filter(lambda x: x%2==0, a) # print(list(b)) # c = [x for x in a if x%2==0] # print(c) #reduce(func,seq) from functools import reduce a = [ 1 , 2 , 3 , 4 , 5 , 6 ] product_a = reduce ( lambda x , y : x * y , a ) print ( product_a )

PYTHON ADVANCED - 07: ITERTOOLS

 HERE, WE WILL LEARN ABOUT ITERTOOLS: NOTE: TRY ALL METHODS/CODES #itertools : product, permutations, combinations, accumulate, groupby, and infinite iterators # from itertools import product # a = [1,2] # b =[3] # c = [5,6] # prod = product(a,c) # # prod = product(a,b, repeat=2) # print(list(prod)) # from itertools import permutations # a = [1,2,3] # perm = permutations(a) # print(list(perm)) # from itertools import combinations, combinations_with_replacement # a = [1,2,3] # comb = combinations(a, 2) # print(list(comb)) # combwr = combinations_with_replacement(a, 2) # print(list(combwr)) # from itertools import accumulate # import operator # a = [1,2,5,3,4] # # acc = accumulate(a) # # acc = accumulate(a, func = operator.mul) # acc = accumulate(a, func = max) # print(a) # print(list(acc)) # from itertools import groupby # def smaller_than_3(x): #     return x<3 # a = [1,2,3,4] # groupobj = groupby(a, key=smaller_than_3) # for key,value in groupobj: #     prin...

PYTHON ADVANCED - 06: COLLECTIONS

 HERE, WE WILL LEARN ABOUT COLLECTIONS: NOTE: TRY ALL  TYPES/CODES #collections : counter, namedtuple, orderedict, defaultdict, deque # from collections import Counter # a = "aaaaaaaaaabbbbbbbbbbbbcccccccc" # mycounter = Counter(a) # print(mycounter) # print(mycounter.items()) # print(mycounter.keys()) # print(mycounter.values()) # print(mycounter.most_common(3)) # print(mycounter.most_common(3)[0]) # print(list(mycounter.elements())) # from collections import namedtuple # Point = namedtuple('Point', 'x,y') # pt = Point(1,-4) # print(pt.x , pt.y) # from  collections import OrderedDict # ordered_dict = OrderedDict() # ordered_dict['a'] = 1 # ordered_dict['b'] = 2 # print(ordered_dict) # from collections import defaultdict # d = defaultdict(int) # d['a'] = 1 # d['c'] = 2 # d['b'] = 3 # print(d['c']) from collections import deque d = deque () d . append ( 1 ) d . append ( 2 ) d . appendleft ( 3 ) print ( d ) # d...

PYTHON ADVANCED - 05: STRINGS

 IN THIS TUTORIAL, WE WILL SEE STRINGS: NOTE: TRY ALL METHODS/CODES WHICH ARE COMMENTED OUT. #strings: ordered,immutable, text representation # mystring = "I'm a Programmer" #"hello universe" # substring = mystring[0::2]  #--> slicing operator # print(substring) # print(mystring[0]) # name = "Tom" # sentence = name + ", " + mystring # print(sentence) # for i  in mystring: #     print(i) # if "a" in mystring: #     print('yes')     # else: #     print("no")     # my_string = "hello world" # my_string = my_string.strip()  #-->removes wide spaces # print(my_string) # print(my_string.upper()) # print(my_string.lower()) # print(my_string.startswith('hello')) # print(my_string.endswith("world")) # print(my_string.find('o')) # print(my_string.find('pp')) # print(my_string.count("l")) # print(my_string.replace("world", "Universe")) # string = ...

PYTHON ADVANCED - 04: SETS

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT SETS: NOTE: TRY ALL METHODS WHICH ARE COMMENTED OUT(GREEN LINES) #sets : unordered, mutable, no duplicates # myset = {1,2,3,1,3} # print(myset) # mySet = set([1,2,3]) # print(mySet) # myset = set("hello") # print(myset) # myset  = set()  #{} = class dict # print(type(myset)) myset = set () myset . add ( 1 ) myset . add ( 12 ) myset . add ( 13 ) # if 1 in myset: #     print("yes") # else: #     print("no")     # for i in myset: #     print(i) #  myset.remove(13) # myset.pop() # print(myset) # odds = {1,3,5,7,9} # evens = {0,2,4,6,8} # primes = {2,3,5,7} # u = odds.union(evens)  #--> combines elements of two sets # print(u) # i = evens.intersection(primes) # print(i) # setA = {1,2,3,4,5,6,7,8,9} # setB = {1,2,3,10,11,12} # diff = setB.difference(setA) # print(diff) # diff = setA.symmetric_difference(setB) # print(diff) # setB.update(setA) # print(setB) # setA.intersection_update(se...

PYTHON ADVANCED - 03: DICTIONARIES

 IN THIS TUTORIAL, YOU WILL LEARN ABOUT DICTIONARIES. NOTE: TRY ALL METHODS/CODES WHICH ARE COMMENTED OUT.(GREEN LINES) #dicitonary : key-value pairs, unordered, mutable mydict  = { "Name" : "Shayan" , "city" : "Nawada" } mydict2 = dict ( name = "afrida" , roll = "34" ) # print(mydict) # mydict["email"] = "papa@gmail.com" # print(mydict) # value = mydict["name"] # print(value) # mydict2 = dict(name="shayan" , city="nawada") # print(mydict2) # del mydict["city"] # print(mydict) # mydict.pop("city") # print(mydict) # if "name" in  mydict: #     print(mydict["name"]) # try: #     print(mydict["lastname"]) # except: #     print("error")     # for key in mydict: #     print(key) # for key, value in mydict.items(): #     print(key,value) # mydict_cpy = mydict # print(mydict_cpy) mydict . update ( mydict2 ) print ( mydic...

PYTHON ADVANCED - 02: TUPLES

 IN THIS TUTORIAL,  YOU WILL LEARN ABOUT TUPLES: NOTE: TRY ALL METHODS/CODES WHICH ARE COMMENTED OUT(GREEN LINES) # Tuple : ordered, immutable, allows duplicate elements # myTuple = ("max", "ashish", "shayan") # print(myTuple) # item = myTuple[-3] # print(item) # for i in myTuple: #     print(i) # if "max" in myTuple: #     print("yes") # else: #     print("no")         # print(len(myTuple)) # print(myTuple.count('shayan')) # print(myTuple.index('shayan')) # myList = list(myTuple) #--> converts tuple to list # print(myList) # mytuple = tuple(myList) #--> converts list to tuple # print(mytuple) # c = myTuple[:3] # print(c) # name1, name2, name3 = myTuple # print(name1) # print(name2) # print(name3) # import sys # my_list = [0,1,2,"hello", "shayan"] # my_tuple = (0,1,2,"hello", "shayan") # print(sys.getsizeof(my_list), "bytes") # print(sys.getsizeof(my_tuple...

PYTHON ADVANCED - 01: LISTS

 IN THIS TUTORIAL, WE WILL LEARN ABOUT LIST:' NOTE: YOU MUST TRY ALL CODES WHICH ARE COMMENTED OUT(IN GREEN LINES) # list : ordered, mutable, allows duplicate elements # myList = ["Shayan", "Akhtar", "Abedeen"]             # 0           1           2             # -3         -2          -1 # print(myList) # for i in myList: #     print(i)    #--> print each element of list in new line 1 by 1 # if "Shayan" in myList: #     print("yes") # else: #     print("no")     # item = myList[-3] # print(item) # myList2 = [5, True, "apple", "apple"] # print(myList2) # print(len(myList)) # myList.append("Afrida") # print(myList) # myList.insert(1, "Siddiqua") # print(myList) # a = myList.pop() # print(a) # print(myList) # a = myList.remove("Abedeen") # print(myList) # myList.clear() # print(...