Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Python Notes and Cheat Sheet with Examples, Cheat Sheet of Programming Languages

Python Notes and Cheat Sheet with Examples

Typology: Cheat Sheet

2021/2022

Available from 01/13/2022

abhishek-pratap-singh
abhishek-pratap-singh 🇮🇳

1 document

Partial preview of the text

Download Python Notes and Cheat Sheet with Examples and more Cheat Sheet Programming Languages in PDF only on Docsity! tut6(comment and escape sequence) print(type(var1) ) print(type(var2) ) print(type(var3) ) print(var2+ var3) print(vari+var4) print(type(var2+ var3)) print(var5+var6) ee OMt Ole Dead OLED) print(str(var2)+str(var3) ) to take input in python input is taken by de ("Enter no.") input() eVisit MD) method input("en in") ou entered ",a) tut8 (string slicing) Strings in Python are immutable meaning you cannot replace parts of them. string fun — findall, search, split, sub, finditer print(mystr) #print e strin, print(mystr[2]) #print that ind print(len(mystr)) #print the leng print(mystr[@ ]) #print from includir arti i and upto last ind cluding) print(mystr[@:10:2]) #print with escapi one characters if instead of 2 hae ae 7 foyarm ale Geta t e the string then print from starti o last print(mystr[: eee eeu ee eal 0 last skipir print(mystr[@:]) #print from startin print(mystr[::]) #print from s print(mystr.isalnum()); #check whether it is alpha numeric or no salpha()); #check whether it is alpha or not t false b/c conta .endswith("boy")) #check whether it ends with in yatasely print(mystr.count("o")) # .capitalize()) # print(mystr.find("is")) #, print(mystr.lower()) #con -upper()) #convert in uppe -replace(" good od tut9 (list,tuple and list func.) grocery =["harpic","vim bar", " AOD ets aM NY) print(grocery) #print complete list print(grocery[3]) #print at that index assume as a numbers =[5,5,5,8,3,7,4] list1 = [5,7,3] if 5 in list1: print( ») if 15 not in list1: print( ») c = int(input( )») if c>b : print( c = int(input( )») flannel ) if c>b else print( p) a oral dict(list2) ie) pee 1 ng yo print(item) for item,numb in list2: print(item, eos ,end= foyarmaiag ,dict1) for item,numb in dict1.items(): print(item, Paleied) prac = [ Py 9Bo055]| for item in prac: if(str(item).isnumeric() and item>6): print(item) GIECE flannel for item in range(0,6,2): print(item, end= ») tut 18 (break, continue) i=0 continue print(i, end= ») print(i, end= ») eo tut21(Operators) tut 22 ( function and docstring) def function(a, b): print( def function2(a,b): average = (a+b)/2 print(average) ft-ne0 eer Wd art 22 print(function(7, 10)) print(function2(4,8)) print(function2._doc__) print(function2.__code__) print(function. doc __) tut23 (exception handling) a aay Leia ») b aay Leia ») Lav flannel ,int(a)+int(b)) except Exception as e: 10 11 12 Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file 1 writing. wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates new file for writing. wt Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exi creates a new file for reading and writing. wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file do not exist, creates a new file for reading and writing. Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the appe mode. If the file does not exist, it creates a new file for writing. ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. Thatis, the f is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file ope in the append mode. If the file does not exist, it creates a new file for reading and writing. ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exis The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. tell and seek tell — returns the position of pointer in terms of character seek- it changes the position of pointer to given position (f.tell()) print(f.readline()) print(f.readline()) f.close() using with block it is same as f = open and f.close() with open("avi.txt") as f: #inside open you can also pass opening mode f.readlines() print(a) inside this with block you can do your work related to file and on coming outside of this block it automatically close the file. Scope, global variable and keyword Eade ee yl ane 1 = 10 #Globlal def function1( #1=5 # print(1) ae tae ae a 7 E it will not in lo Sa ae error""" fasta) ety) function1("This is me") yaaa @D) def avi2(): Cree Ret akc Teena ae roe ON SIT ace pert} ao Pe Cee a Tan Pare aeae cea EN Re meee #h foyarmaiag 9X) # here it will print pent Joie g i() fn has x in its ill execute this one. avi() print(x) #it will print lambda or anonymus function it is a one liner function without any name a =[[1, 14], [5, 6], [8,23]] a.sort(key=lambda x:x[1]) print(a) sort or sorted function can receive two arguments “ key = none “ and “reverse = False” none and false is by default if we not pass if we make reverse = true it will sort in descending order and key if we pass any function name then it pass each element of that list or tuple in function and then sort according to the returned value of function and instead of passing a fn you can also write lambda function using modules to install a module open windows powershell and run it as administrator then write “pip install flask” to install flask for other write its name fun(normal_variable, *myargs, **mykwargs) : print("This is normal variable",normal_variable) print("Now these are args variable") am a-11 Tele print(item, en print("Now these are kwargs with keyworded variable") SARE AUICS Tao ela ee 1d print(f"{key} is related with {value} using key value pair.") fun("Avishek", *[ "Avi", "Abhay", "Raushan", "Varun"],**{"Avi":"7479", "Abhay" a) ys cen = time.time() (k<3): print("This is me") kt= print("While loop ran , time.time() - tial, "Seconds") Aeon ime.time() ae range(3): print("This is me") print("For loop ran in", time.time() - itial2, "Seconds") localtime = time.asctime(time.localtime(time.time())) print(localtime) print(time.time()) print(time.localtime(time.time())) print(time.asctime(time.localtime(time.time()))) A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them. This is one of the most important tools that most of the Python developers use. Why do we need a virtual environment? e Imagine a scenario where you are working on two web based python projects and one of them uses a Django 1.9 and the other uses Django 1.10 and so on. In such situations virtual environment can be really useful to maintain dependencies of both the projects. e Imagine another scenario you have create a program using some functions of current versions of pandas or sklearn libraries and then after some year that libray got updated and that function is removed and when you use the same program it will not behave normally. So we can also keep a copy of current versions of libraries and some other tools also in virtual environment which are used by our program. Virtual Environment should be used whenever you work on any Python based project. It is generally good to have one new virtual environment for every Python based project you work on. So the dependencies of every project are isolated from the system and each other. How does a virtual environment work? We use a module named virtualenv which is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. Installing virtualenv © Opena folder(where you want to create virtual environment) then press shift and right click >Open powershell window here e After opening it pip install virtualenv ° Then virtualenv my_name e It has created a new virtual environment and it is independent like a new born baby. And you can also check there is folder of my_name in the selected folder. ¢ And if you want to create a virtual environment that is not like new born baby or it should contain all site packages of your system interpreter then use command virtualenv --system- site-packages my_name2 e You can activate it by opening that folder > Scripts > activate.bat. Or from windows powershell .\my_name\Scripts\activate ¢ Now your virtual environment has been created. Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active. ¢ Now you can install your packages using command pip install its_name. ¢ To install a particular version suppose to install Django 1.9 use command pip install Django==1.9 ¢ However if want to share our program with its dependent package , generally we don’t share it with whole packages due to its large size. So we keep a record of packages that is used by our program in our requirements.txt file. ¢ To create the requirements.txt file we use command pip freeze > requirements. txt ¢ Or to install the packages of someone else program keep that requirements.txt file in that folder and use command pip install -r .\requirements.txt © Once you are done with the work, you can deactivate the virtual environment by command deactivate. How to execute your program in new virtual environment already created(in pycharm) ? © Open pycharm>File>Open ¢ Choose your virtual environment folder and select/open in pycharm. ¢ Now you can create any program and simply execute as you do normally. Enumerators Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method. 11 =["item1","item2","item3","item4","item5","item6","item7","item8"] for index,item in enumerate(11): print(f"{item} is on index number {index+1}") How import works And if _name_==‘_main When we write import means we are putting the codes of that file in our file we can also import our own file. __name_ isa built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement. If the script is executed in its file then name is main but when imported in some file and executed then its name is its file name . Sometimes we define some very useful function and do some work in a file and if we import that file then it is again executed there, which is not required we need only those defined function for some other operations. In such case we use if __name__ ==’__main__’ because when it is imported in some other file then it’s name will be different and the condition becomes false and if it is executed in same file then only condition will be true and it’s code will be executed Filed ¢ At first step, first two elements of sequence are picked and the result is obtained. ¢ Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored. ¢ This process continues till no more elements are left in the container. ¢ The final returned result is returned and printed on console. functools reduce ra iTennana print(reduce( : atb,lis)) ilernana print(reduce( Zip() and Unzip() The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity. Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator. ed roll_no UE Tae mapped zip(name, roll_no, marks) print (mapped) cael) mapped: print(item[1]) mapped = set(mapped) Tanne print (mapped) name = [ roll_no = ig marks = [40 mapped = zip(name, roll_no, marks) = list(mapped) (*mapped) Decorators A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. It takes a function as an argument and we can do something inside a decorator and with that function. To add a decorator use the @ symbol and name of that decorator before the definition of that symbol. def deci(func1): def nowexec(): print( "Executing now") func1() print( "Executed" ) otal tLe) nb te ea Oe print("Harry is a good boy") who_is_harry() Object Oriented Programming Class Like C/C++ same type of class is here, Here we can add some properties ( function or variables ) to a particular object without changing in template of class. Employee: no_of_leaves = 8 EW aM II} abhi.name = print (avi.name) print (avi.no_of_leaves) print (abhi.no_of_leaves) print (Employee.no_of_leaves) avi.no_of_leaves = 5 iTannaial @ ») print(avi.no_of_leaves) print (abhi.no_of_leaves) print(Employee.no_of_leaves) Output DN eRT-L To get the details of class or object “its_name.__dict__” Self and _ init_()(constructor) Constructor initialise the object. When nothing in passed as argument inside the methods (functions) then there is “self” has to be passed, self is calling object and inside the function we access it by using dot operator with self. __init_() is constructor which takes “self” argument which is used to acess its members. Employee: no_of_leaves = 8 Class method as a alternative constructor We can also use class method as constructor. It can be better explained by following example. Employee: no_of_leaves __init__(self, aname, asalary, arole): TOR aD OR et Nee T SET O2 self.role = arole printdetails(self): f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}" @classmethod change_leaves(cls, newleaves): cls.no_of_leaves = newleaves @classmethod from_dash(cls, string): cls(*string.split("-")) Employee("Harry", 255, “Instructor") Employee("Rohan", 455, “Student") (karan.no_of_leaves) Single level inheritance Source code: class Employee: no_of_leaves = 8 def (self, aname, asalary, arole): TO A OR eS Teva self.role = arole (self): @classmethod def (cls, newleaves): cls.no_of_leaves = newleaves @classmethod def (cls, string): return cls(*string.split( »») @staticmethod def (string): ine + string) class Programmer (Employee) : no_of_holiday = 56 def (self, aname, asalary, arole, languages): TO A OR eS Teva self.role = arole self.languages = languages (oon xk a harry = Employee( rohan = Employee( shubham = Programmer( D karan = Programmer( 9 Vit, print(karan.no_of_holiday) Multiple Inheritance Source Code: class Employee: no_of_leaves = 8 Na) (self, aname, asalary, arole): TO A OR eS Teva self.role = arole (self): cha @classmethod def (cls, newleaves): cls.no_of_leaves = newleaves @classmethod def (cls, string): return cls(*string.split( »») @staticmethod def (string): erat + string) class Player: Nl) no_of_games = 4 def change _leaves(cls, newleaves): cls.no_of_leaves = newleaves @classmethod def from_dash(cls, string): return cls(*string.split( @staticmethod def printgood(string): print("This is good " + string) emp = Employee(“harry", Pee dae) print(emp. Employee __pr) << But in private python do name mangling means to access you have to write in this format. polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Super() and Overriding When we create an object( or instance) of a class and call any variable or method then first it search for instance variable or method in that class and if it is not found then it search for instance variable or method in its parent class from where it is derived and if there is no any instance variable or method is present then it search for class variable or method in that class and if it is not found then in its parent class from where it is inherited. And if none of instance/class variable or method of that name is present then it gives error. Overriding When we override any method in its child class then that method (present in parent class) is completely neglected in program. Like in below ex if we override the constructor then first is neglected and calling special varialble will throw error. a (ol eelaw Ecler ae ela id .classvar1 = print (b.classvar1) print (b. special ) So to execute constructor of both class we have to use super() , super() provides the access to those methods of the super-class (parent class) which have been overridden in a sub-class (child class) that inherits from it. But if we write super() and use constructor of parent(super) class in starting of constructor of child class then first it will execute the super() class constructor but if in last of constructor of child class then it will be executed in last. See ex Case 1: A: classvari1 = -Classvari1 = ey o)-ton ETCH Cos FEES oh __init__( super()._init__() le Peel FTES oe a = A() b = B() print(b.classvar1) print(b. special) Output: Instance var in class B special variable Here first super class constructor executed which made b.classvar1 = “Instance var in class A” because it is written first inside the constructor of B and then after its constructor executed due to which it changed to b.classvar1 = “Instance var in class B” because of the line .classvari = in its constructor because it is written after the super() means it executed after the constructor of parent class is executed so it changed the value of b.classvar1. Case 2: A: classvari1 = Output: Instance var in class A special variable Here first constructor of class B executes in which its 2"° line made b.classvar1 = “Instance var in class B” and then it called constructor of parent (super) class using super() and then 2" line of constructor of A made b.classvar1 = “Instance var in class A” so final result in case 2 is b.classvar1 = “Instance var in class A”. Diamond Shape Problem This is a inheritance map and we have to understand how and which run on doing diamond shape inheritance. class A: def met(self): print("This is a method from class A") class B(A): def met(self): print("This is a method from class B") class C(A): def met(self): print("This is a method from class C") class D(C, B): This method is called when ) function is invoked on the object, in that case, __repr__() function must return a String otherwise error will be thrown. If we write “print(function_name)” then first it will prefer to print “ str method” and if it is not available and repr method is available then it will print “repr method”. But if we write str(function_name) then it will print str method and if repr(function name) then repr method. Operation Syntax Function Addition a+b add(a, b) Concatenation seql + seq2 concat(seql, seq2) Containment obj in seq contains (seq, obj) Test Division a/b truediv(a, b) Division a//b floordiv(a, b) Bitwise And aé&b and_(a, b) Bitwi itwise a*b xor(a, b) Exclusive Or Bitwi itwise ~a invert (a) Inversion Bitwise Or a lb or_(a, b) E aa. xponentiatio oT SERED) n Identity ais b is_(a, b) Identity ais not b is_not(a, b) I ndexed obj[k] =v setitem(obj, k, v) Assignment I ndexed del obj [k] delitem(obj, k) Deletion Indexing obj [k] getitem(obj, k) Left Shift a<<b Ishift(a, b) Modulo a%b mod(a, b) Multiplication a * b mul(a, b) Operation Matrix Multiplication Negation (Arithmetic) Negation (Logical) Positive Right Shift Slice Assignment Slice Deletion a>>b seq[i:j] = value 8 del seq[i:j] Function matmul(a, b) neg(a) not_(a) pos (a) rshift(a, b) setitem(seq, values ) slice(i, j), delitem(seq, slice(i, j)) Slicing seq[i:j] getitem(seq, slice(i, j)) Fomatting s % obj mod(s, obj) Subtraction a-b sub(a, b) Truth Test obj truth (obj) Ordering a<b 1t(a, b) Ordering a<=b le(a, b) Equality a == eq(a, b) Difference al=b ne(a, b) Ordering a >=b ge(a, b) Ordering a>b gt(a, b) Here for “a+b” function is add(a,b) If we write (self, ot eee ele ae lene el then add will be overloaded for other type Example: avishe _init__( TET eee MT BET THe eet lag -role = role ilernana other): leil-ie ( other): PtH eee APT PB Ta7 avishek(f"{str(a).lower()+ eS EMP NaI Ty 6 print(a. Picea print (a/7T@) Here | overloaded add “+” with ofte-operand of avishek type and other of str type and it will also return of avishek type addition of these two will return of type avishek and which is further added with another string. Abstract class or @abstrcat method An abstract class can be considered as a blueprint for other classes, allows you to create a set of methods that must be created within any child classes built from your abstract class. A class which contains one or abstract methods is called an abstract class. An abstract method is a method that has declaration but not has any implementation. Abstract classes are not able to instantiated and it needs subclasses to provide implementations for those abstract methods which are defined in abstract classes. While we are designing large functional units we use an abstract class. When we want to provide a common implemented functionality for all implementations of a component, we use an abstract class. Abstract classes allow partially to implement classes when it completely implements all methods in a class, then it is called interface. Why use Abstract Base Classes : Abstract classes allow you to provide default functionality for the subclasses. Compared to interfaces abstract classes can have an implementation. By defining an abstract base class, you can define a common Application Program Interface(API) for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations, such as with plugins in an application, but can also help you when working on a large team or with a large code-base where keeping all classes in your head at the same time is difficult or not possible. How Abstract Base classes work : In python by default, it is not able to provide abstract classes, but python comes up with a module por PSP) This was something called getters. But what when we want to change the fname or Iname when email is changed to ( or to set/access the private members with some condition) Sono ne Pat MeL) meee And to delete this email method we have to use delete but in object oriented programming generally we don’t delete we set it None. Peru ie) = But setting it only None gives None.None@gmail.com when we print email so in property (getter) we have to change something - Iname== . fname pe EIS We can also use it to access private variable class Geeks: def init (self): self. age = 0 # using property decorator # a getter function @property def age(self): print ("getter method called") return self. age # a setter function @age. setter def age(self, a): if(a < 18): vrais alueError("Sorr s bel g iteric print ("setter method called") self. age =a mark = Geeks() mark.age = 19 print (mark. age) Object Introspection Introspection is the ability to determine the type of an object at runtime. It is one of Python’s strengths. Everything in Python is an object and we can examine those objects. dir In this section we will learn about air and how it facilitates us in introspection. It is one of the most important functions for introspection. It returns a list of attributes and methods belonging to an object. Here is an example: Our introspection gave us the names of all the methods of a list. This can be handy when you are not able to recall a method name. If we run dir() without any argument then it returns all names in the current scope. type and id The type function returns the type of an object. For example: # Output: <type ‘int'> id returns the unique ids of various objects. For instance: name = “Yasoob” print(id(name) ) # Output: 139972439030304 inspect module The inspect module also provides several useful functions to get information about live objects. For example you can check the members of an object by running: import inspect print(inspect.getmembers(str)) # Output: [('_add_', <slot wrapper '_add_' of ... Introspection of previously defined Employee class (inspect.getmembers (skillf) ) Iterator and Genarators Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory. Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. And Generators can be iterated only once. Iterable - _iter_() or __getitem_() # applying these fn gives iterator Iterator - next__() # it will produce next element of that sequence Iteration - it is process of iterating def gen(n): ("Your item was not found") Function Caching Function caching is a mechanism to improve the performance by storing the return values of the function. So that each time when they are called with same set of arguments, It will return the value from the cache instead of executing the whole function again. To use it we have to import Iru_cache from functools module import time from functools import Lru_cache @Lru_cache(maxsize=32) #it will remember Last 32(here) results some_work(n): time.sleep(n) ii} ‘_main_': ("Now running some work") some_work(3) some_work(1) some_work(6) some_work(2) ("Done... Calling input() some_work(3) (ea) try, except with finally and else try and catch is same as we learnt before. But if we want to write some code which has to be executed any how whether it throws error or not then we write it inside “finally”. Finally is generally used for code clean up. And the code written inside “else” executes only when if except block doesn’t execute. Means only one of the “else” or “except” will execute. We can use more than one except statement for a single try. Coroutines def searcher(): import time book = "This is a book on harry and code with harry and good" time.sleep(4) aaa) text = (yield) #from this line it will be identified as coroutines if text in book: print("Your text is in the book") iB print("Text is not in the book") Search = searcher() Esa Pee nn eT print("“search started") next (search) Eis ans et NC) YO) print("“Next method run") search. send("harry" #from this line it will be send data every time to text #and that fn will be executed from there not from Boot ae 1 lael tO) #it will close, when you want to release the memory close #it and but when you need again you can start but it will #take time again to initialise using search = searcher() search. send( "harry" ) Os Module OS stands for operating system Using this we can create folder, rename file, open file and ........ os.path.splitext() method in Python is used to split the path name into a pair root and ext. Here, ext stands for extension and has the extension portion of the specified path while root is everything except ext part. import os (dir(os)) (os.getcwd()) os.chdir( »} #it will change the directory (os.getcwd()) \ ) (os. listdir( )) os.mkdir( >) os.makedirs( os. rename( Pla wo) ae 4-1 Py or Lose onal Pu oY Lo) G3 od Py oY 1-0 .path.exists( Py oreo ay eG Py ode eb nal Practice Problem import os def prettifier (path, filename, format): 1s = os.listdir(path) os.chdir(path) format_file = [item for item in ls if item.endswith( format) ] to_rename_file = [item for item in ls if not item.endswith(format) and Pees RET a ee (filename) restricted_word = f.read() £.close() restricted_word = restricted_word.split( for item in to_rename_file: if item.split( )[@] not in restricted_word: renamed_item = item.split( »} renamed_item[@] = renamed_item[@].capitalize() renamed_item = «join(renamed_item) os.rename(item, renamed_item) | would get this error: TypeError: expected string or buffer json.loads() json.loads() deserialize string. So in order to use json.loads | will have to pass the content of the file using read() function, for example, using content.read() with json.loads() return content of the file, with open("json_data.json", "r") as content: print(json.loads(content.read())) Output, {u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}} That's because type of content.read() is string, i.e. <type ‘str'> If | use json.load() with content.read(), | will get error, with open("json_data.json", "r") as content: print(json.load(content.read())) Gives, AttributeError: 'str' object has no attribute 'read' So, now you know json.load deserialze file and json.loads deserialize a string. Json.dumps() Serialize obj to a JSON formatted str Similar to json.load{() , json.dump() convert obj to json formatted file. Difference between json.loads() and json.dumps() Json.loads() convert string to python dictionary object(like json object but not actual because it is not javascript compataible) whereas json.dumps() converts a object to a string which javascript compatible (or json formatted string) Ex —- Akhbaar padh k sunao For me — my key is kept in my news website js file , this is someone else key it may not work. Tt win32com.client data = r.json() data = data[ beer items (Fler print(items[ )) to_speak = items[ ].split( 2] a aay a speak ( aad speak ( speak(to_speak) Pickle module The pickle module is used for implementing binary protocols for serializing and de-serializing a Python object structure. e Pickling: It is a process where a Python object hierarchy is converted into a byte stream. e Unpickling: It is the inverse of Pickling process where a byte stream is converted into an object hierarchy. Module Interface : e dumps() — This function is called to serialize an object hierarchy. e —loads() — This function is called to de-serialize a data stream. For more control over serialization and de-serialization, Pickler or an Unpickler objects are created respectively. Here also load()/loads() and dump()/dumps() are there and diff is same like in json module as described in previous chapter. In loads “s” stands for string The loads function does not take the file path, but the file contents as a string while load takes a file object. pickle. load(fileobj) print (mycar) print (type(mycar) ) Regular Expressions In regular expression we use raw strings means no special sequences. To tell python interpreter that this string is raw string please interpret it literally we keep “r’” in starting of that file. Dot “.” Means any character as shown in table below: Meta Characters [] A set of characters [D]an - Matches “Dan”, not very useful. [DBJan - Matches “Dan” and “Ban” (first letter can be "D" or "B"). [DBTP]an - Matches “Dan”, “Ban”, “Tan”, and “Pan”. Da[ng] - Matches “Dan” and “Dag” (last letter can be “n" or "g"). [Dan] - Matches single character “D”, or “a”, or “n”. Meaning it will not match the entire string "Dan", only one single character (probably not what you wante \ Signals a special sequence (can also be used to escape special characters) . Any character (except newline character) 4 Starts with S$ Ends with * Zero or more occurrences + One or more occurrences {} Exactly the specified number of occurrences | Either or () Capture and group Special Sequences \A Returns a match if the specified characters are at the beginning of the string \b Returns a match where the specified characters are at the beginning or at the end of a word r"ain\b" \B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word \d Returns a match where the string contains digits (numbers from 0-9) \D Returns a match where the string DOES NOT contain digits \s Returns a match where the string contains a white space character \S Returns a match where the string DOES NOT contain a white space character \w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) \W Returns a match where the string DOES NOT contain any word characters \Z Returns a match if the specified characters are at the end of the string Set Description [arn] Returns a match where one of the specified characters (a, r, or n) are present print (email) How to Convert .py file to .exe? Follow these step e Make a new folder the Shift + Right Click -> Open powershell here e Install pyinstaller module by using “pip install pyinstaller” ¢ Create a .py file in that folder ¢ In Power Shell write “pyinstaller pythonapp.py” here pythonapp is name of file you have to keep your file name. e It will create some folder, insider “dist” folder (dist means distribution) another folder was there whose name was same as your file name, You can share that complete folder(whose name is same as your file) to share your app. ¢ That folder contains multiple files and one exe file, other files are required for this exe file. To create one file instead of these multiple file e The folder you created at the starting open power shell window there and type “pyinstaller - -onefile pythonapp.py” here pythonapp is name of file you have to keep your file name. e And inside dict folder you will get your app( exe file). Raise in python We can also raise some error if we want, it is useful in those situation when something went wrong and without that further execution of program doesn’t matter so we will raise the error at time and save the time and resources. yell a.isnumeric(): Exception( emia a}") E b = int(input( iid ZeroDivisionError( print(a/b) Some builtin errors: MemoryError: It comes when some command or operation run out of memory or exceeds memory limit. Keyerror: Raised when a key is not found in the dictionary. Type error --> jab variable ka type wrong hoga . e.g Print (sum(5+"4")) Value error-->. Jab variable ka type sahi ho lekin galat value pass ki gayi ho e.g print(int("one")) Name error: variable declaration ke pahle ki name use ho e.g print (name) assert(condition) - jab condition false ho to exception raise hogi OSError: jab koi operating system related problem aati hai. PermissionError: jab koi chij ko open or file ko edit karne ke liye permission nahi hota IndentationError: jab galat Indentation ho FileNotFoundError----yh error tb aata hai jb aap koi aise file ko open kr rhe ho jo ki.. Nhi hai aapke folder me.. ImportError - jab interpreter ko koi imported module nhi milta hai tab ye Exception raise hota hai. AttributeError-->Raised when an attribute reference or assignment fails e.g list1.pow() list has no attribute pow() EOF Error:-jab input function file ka end ma chala jata hai BrokenPipeError- A subclass of connection error, raised when tring to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Overflowerror :-Arithmetic operation bahut bada hota he or intergers memory me nahi leta he tab raise hoti he Recursionerror:-jab interpreter jyada recursion ka code likh dete he tab raise hoti he UnboundLocalError - yeh tb ata ha jb koi function ya variable ko call krta ha pr vo variable ya function phle code m define nhi hua hota TabError: ya indentation ma tabs or khali jaghao ka inconsistent istemal hota ha ya indentation error ki 1 subclass ha UnicodeError - jab Unicode se sambandhit encoding ya decoding error ho Command line Utility We can use this when we are programming in other language and we need some use of any program which is created in python then we can execute this program from cmd . Suppose this is our program for which we are crating our command line utility. And its name is “cmdUtillity_ptyhon.py” ,you can choose some diff name. argparse sys (Cle-4 elo ine te ar Caerleon ine te ar Caerleon ine te ar Caerleon ine te ar else: ase laa) if _name_ == parser = argparse.ArgumentParser() [elet-leee-lele Melee an @ , type=float, default=1.0, ite [elet-leee-lele Melee an @ , type=float, default=3.0, ite [elet-leee-lele Melee an @ Pee aree (nal ite args = parser.parse_args() sys.stdout.write(str(calc(args))) #this line will print on screen To execute from powershell open it and then PS C:\Users\ Abhishek Pratap> cd ~ PS C:\Users\ Abhishek Pratap> cd .\PycharmProjects\pythontutorial\, PS C:\Users\ Abhishek Pratap \PycharmProjects\pythontutorial> python .\cmdUtillity_python.py --x 7 - -y8 --o add user_input = choice = choice. lower() == : calculate(user_input) choice. lower() == [aston Kote ( (choice.lower() == O Problem -3 Reverse the list with three methods. myreverse(food_list): i] (len(food_list)//2): food_list[i], food_list[ (food_list)-1-i] = food_list[ (food_list)-1- PPR a food_list a yes mT t= [ food_list.reverse() (food_list) food_list.reverse() (food_list[::-1]) (myreverse(food_list)) Problem 4 Find next palindrome no. next_palindrome(num) : num = (num) n= (num) left_half = num[:n//2] LP right_half = num[n//2 +1:] right_half = num[n//2:] ispalindrome (num) : [eT tad fe str(int(num)+2) Laid str(int(left_half)+1) + str(int(left_half)+1)[::-1] str(int(left_half)+1) + num[n//2] + str(int(left_half)+1)[::-1] int(left_half) > int(right_half): (sa ail Tae eae ae taal Sed eee left_half + num[n // 2] + left_half[::-1] Laid str(int(left_half)+1) + str(int(left_half)+1)[::-1] str(int(left_half)+1) + num[n//2] + str(int(left_half)+1)[::-1] (num): num = str(num) num == num[::-1] aT test_case = int(input( Exception e: ilewnana exit() test_case>0: test_case -= 1 num = int(input( Exception cy print( exit() print(next_palindrome(num) ) Problem 7 Search result for a query (sentence1, sentence2): words1 = sentencel.strip().split( words2 = sentence2.strip().split( score = @ for word1 in words1: for word2 in words2: if word1.lower() == word2.lower(): score += 1 return score if _name_ == sentences = [ query = input( ») scores = [mathingWords(query, sentence) for sentence in sentences] sortedSentScore = [sentScore for sentScore in sorted( (scores, sentences), reverse=True) if sentScore[@] !=0 ] print(f for score, item in sortedSentScore: print(f
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved