Python Cheat Codes
Python Cheat Codes
Is any port number 0-65535, Type < IP address of PC>:
in the phone's browser, You can now browse the files in the PC directory, import antigravity import this ‘Swapping variables is a breeze in Python, No offense, Java! Use a sequence as function arguments Via asterisk operator *. Use a dictionary (key, value] via double asterisk operator “* Use unpacking for multite assignment feature in Python Use unpacking to merge two dletionaries Into a single one Open the cor Beautiful is better than ugly. ab abba ne", ‘Alice def F(x, ys 2) CTL, 3, 4]) FOCZ! 4 return x+y * 2 yah a, "= (2, 2,3, 4 5] xe(‘Alice’ : 18} "Bob : 27, ‘Ann’ : 22) (hey) finxter ries xked in your web browser Explicit is a= ‘Alice b= "Jane" 3 3 asi b= 12,3, 4, 5] z= (Alice: 18, Bob": 27, "Ann*: 22}Classes Instance sett Creation Python Cheat Sheet: Classes “A puzzle a day to learn, code, and play” + Visit finxter.com Description A class encapsulates data and functionality: data as attributes, and functionality as methods. tis a blueprint for creating concrete instances in memory. Instances Class aS coe OE Methods commands barktreg) You are an instance of the class human. An instance is @ concrete implementation of a class: all atributes of an instance have a fixed value. Your hair is blond, brown, or black--but never unspecified, Each instance has its own attributes independent of other instances. Yet, class variables are different. These are data values associated with the class, not the instances. Hence, all instance share the same class variable species in the example. The frst argument when defining any method is always the self argument, This argument specifies the Instance on which you call the method, Self gives the Python interpreter the information about the concrete instance. To define @ method, you use self to modify the instance attributes, But to call an instance method, you do not need to specify self You can create classes “on the fly" and use them as logical units to store complex data types. class Enployce() pass ‘enployee = Enployee() cenployee. salary = 122000 enployee.firstnane = "alice" ‘enployee. lastname = “wonderland” print(employee.firstnane + + enployee-lastnane + + str(enployee.salary) + "$ # alice wonderland 122000 Example Blueprint of a dog # class variable shared by all instances species = (“canis lupus") def _init_(self, name, color): self.nane = nane self.state = “sleeping” self.color = color def conmand(self, x): Af x == self.nane: self.bark(2) elif x == "sit™ self.state else: self.state def bark(self, freq): for 4 in range(freq): print("[" + self.nane + "I: Woof") bello alice 10g("bello", “black") jog(“alice", “white") print(bello.color) # black print(alice.color) # white bello.bark(1) # [bello]: Woof! alice.conmand("sit") print(*(alice]: " + alice.state) # [alice]: sit bello. conmand("n0") print("[bello]: " + bello.state) # [bello]: wag tail alice.conmand(“alice") # [alice]: Woof! 4 [alee]: Woof! bello.species += ["wlf"] print (1en(bello. species) len(alice.species)) # True (!) finxterPython Cheat Sheet: Complex Data Types “A puzzle a day to learn, code, and play” + Visit finxtercom Description Example List A container data type thet stores @ 1= [4 2,2] sequence of elements. Unlike strings, lists | print (en(1)) # 3 are mutable: modification possible. Adding Add elements ‘0 alist with () append, (i) [1,25 2]-append(4) # [1, 2, 2, 4] elements | insert, o i ist concatenation. U1, 2, 4]ansert(2,2) # (1, 2, 2, 4] The append operation is very fast. (22) +4) #01, 2 2, 4] Removal | Removing an element can be slower. [1, 2, 2 4]-remove(1) # [2, 2, 4] Reversing | This reverses the order oflist elements. | [1 2, 3]-reverse() # (3, 2, 1] Sorting Sorts a list. The computational complexity [2s 4 2]-sort() # [2, 2, 4] of sorting is supertinear in the no. lst elements Indexing | Finds the first occurrence of an element in [2 2, 4].index(2) # index of elenent 2 is "@" the list & returns its index. Can be slow as [2y 2, 4]-index(2,1) # index of el. 2 after pos 1 is "2" the whole lst is traversed. Stack Python lists can be used intuitively as stack = [3] stacks via the two list operations append) | stack-append(42) # (3, 42] and pop), stack.pop() # 42 (stack: [3)) stack.pop() # 3 (stack: []) Set Asetis an unordered collection of unique basket = {‘apple', ‘eggs’, ‘banana’, ‘orange’} elements (‘at-most-once’). same = set({"apple’, ‘eggs’, ‘banana’, ‘orange’ }) Dictionary |The dictionary is a useful data structure for calories = {"apple’ : 52, ‘banana’ : 89, ‘choco’ : 546} storing (key, value) pairs. Roading and | Read and write elements by specifying the | print(caloriesl‘apple"] < calorses['choco"]) # True writing key within the brackets. Use the keys() and | calorges{ ‘cappu'] = 74 elements | valuesi) functions to access all Keys and print (calories[ ‘banana"] < calories{‘cappu']) # False values of the dictionary. print(‘apple’ in calories.keys()) # True print(52 in calories.values()) # True Dictionary | You can access the (key. value) pairs of @ | for k, v in calories.itens(): Looping _| dictionary with the Atems() method. print(k) if v > 58@ else None # “choco* Membership | Check with the ‘in’ keyword whether the basket = {"apple', ‘eggs’, ‘banana’, ‘orange’} operator | set list, or dictionary contains an element. | print(‘eggs’ in basket) # True Set containment is faster than list print(‘nushroon' in basket) # False containment. List ang Set | List comprehension is the concise Python | # List comprehension Comprehens | way to create lists. Use brackets plusan 1 = [("HL' + x) for x in ['Alice’, "Bob", "Pete']] ion expression, followed by a for clause, Close | print(1) # ["Hi Alice’, ‘Hi Bob", ‘Hi Pete’) with zero or more for or if clauses. Set comprehension is similar to list comprehension. 12 = [x * y for x in range(3) for y in range(3) if xy] print(12) # (8, 0, 2) # Set comprehension squares = { x**2 for x in [0,24] if x <4) # (0, 4} finxterBoolean Integer, Float String Python Cheat Sheet: Basic Data Types “A puzzle a day to learn, code, and play” + Visit finxter.com Description The Boolean data type isa truth value, either True or False. ‘The Boolean operators ordered by priority not x #”ifxis False, then x, else y’ x and y * "if is False, then x, else y x or y *"ifxis False, then y, else x” These comparison operators evaluate to True: <2 and @ ce 1 and 3 > 2 and 2 >=2 and Les and 1 l= 0 # True An integer is a positive or negative number without floating point (e.g. 3). A float is a positive or negative number with floating point precision (e.g. 3.14159265359), ‘The '//’ operator performs integer division. ‘The result is an integer value that is rounded toward the smaller integer number (9.3/2 == 2) Python Strings are sequences of characters. The four main ways to create strings are the following 1. Single quotes "Yes" 2. Double quotes "Yes" 3. Triple quotes (multiline) yes We can’ 4. String method ste(5) == '5' # True 5. Concatenation "Ma" + "hatea” # “wahatea’ ‘These are whitespace characters in strings. © Newline \n © Space \s © Tab Ae Example # 1, Boolean Operations x, y = True, False print(x and not y) # True print(not x and y or x) # True th 2. If condition evaluates to False Af None or @ or @.0 or ** or [] or {} or set(): # None, @, @.8, empty strings, or enpty # container types are evaluated to False print("Dead code") # Not reached ‘iw 3. Arithmetic Operations x y=32 print(x + y) #=5 print(x - y) #=2 print(x * y) # = 6 print(x / y) # = 1.5 print(x // y) # <2 print(x % y) # = 1s print(-x) # = -3 print(abs(-x)) # = 3 print(int(3.9)) # = 3 print(float(3)) # = 3.8 print(x ** y) # = 9 tw 4, Indexing and Slicing = "The youngest pope was 11 years old” print(s(é]) oT print(s[1:3]) # ‘he* print(s[-3:-1]) # ‘ol" print(s(-3:]) # “old” x= s.split() creates string array of words print(x[-3] +" "+ x[-1] +" "+ x[2] + “s") # ‘11 old popes’ #5. Most Important String Methods y=" This is lazy\t\n" print(y.strip()) # Renove Whitespace: ‘This is lazy print(*DrOre*.lower()) # Lowercase: ‘drdre’ print(“attention”.upper()) # Uppercase: ‘ATTENTION’ print("smartphone”.startswith("smart")) # True print("snartphone”.endswith(“phone")) # True print("another".find("other")) # Match index: 2 print("cheat".replace("ch", “n")) # meat” print(’,”.join(("F", "8", “I"])) # °F,8,1" print(len(*Rumpelstiltskin")) # String length: 15 print("ear" in “earth") # Contains: True finxterfinxter The Ultimate Python Cheat Sheet e Keywords Basic Data Structures espn Te a or th oe on 3 tmereone a ene ute: None 00cm stings oremstycontaer icak | cio prenatey ies von ro fone weap [Aneeperapcivesr [iF ii aites creroop Reson fccmlaomsuerar pesteie ty) FS femaxSesaisuze.” princi ® yl + ce Det rene neg ein ounds : lesmpessrva—ih [pesneceioatiany + ie cnaon = tse? Serme | Pbonsngs ae HF Tatening ona Silona or 2 suing croton method: See (2) Ghlhe | for i dn to,ae2y Sree Someatcimanawcaten [y= x= 5 131 ie 13) por steis) = t5* |y.steipin ‘atusbue cee aston earl Newnan sgoiniteer, ty 7181) 4 "SI" a renent (ti feces lenhello wéelg") F Lengths 3S ie scaet in eccuit # fe VD Complex Data Structures ) se _|pscnon ante swe _[owceten aoe oy atone Yeading [Rescate cores by cine) © ear sab Taine _[icetrarswsnin [rs Tawar Sire [Seattconeeren enon [sew ris te # & Samet 1 Ba print isa ia catvvorueenn feehehestema() atts fanwenentBreumsngen |) 'sotx econ As 0 Werten [ina witthe Smkepaor Smwomtanrowraei |2,2 1), sndent2et ster [eis onas fires Se staser nant marberih, Sack [Usrytonimaverais |orack = 15) epuator sppnel areal acksappena a2) © (2, 4 Tier [urecomarnencon ihe Son iss tee trees ssn #1 pore eres, slowed by afer Se [anneaeea olen of fuse Cowwineewor | [22 7 (x * y for x is zange(3) Sor this slomers ot mor eer eritcinses Fange(al it soy) #00 2 enc) tat memberp Ot] sane ~ sot tt annie’ Se campeeson was on toa banana Snir ols comprevesin ae