Python cheatsheet
Python che...
> >References:
Comments
Variables
Data types
Strings
Lists
Tuples
Sets
Dictionaries
Operators
Conditionals
Loops
Functions
Reserved Words
Built-in Functions
Styles
W3schools
Official site
Comments
#Comments can be placed at the end of a line. """ Multi-line string literal not assigned to a variable can be a multi-line comment. """
Variables
No need to declare with any particular type. Created when a value is assigned. Can change type after it has been set. Casting s = str(5) i = int(5) x = float(5) Local -- created inside a function Global -- created outside a function Global -- created inside a function using global global x nonlocal -- non local variable inside nested function
Data types
str s = 'hello' ("hello") bool f = True (False) f = bool(a) False if a = empty (), [], {}, "", 0, None int i = 50000000000000000 float x = 3.14 x = -52.83e-2 complex y = 2+3j range a = range(3, 10, 2) start, stop ,step-->3 5 7 9 len(a)-->4 list a = ["CPU", "HDD", "SSD"] indexed, changeable, allow duplicate values tuple a = ("CPU", "HDD", "SSD") indexed, unchangeable, allow duplicate values set a = {"CPU", "HDD", "SSD"} unindexed, value unchangeable, no duplicate members frozenset a = frozenset({"CPU", "HDD", "SSD"}) unchangeable set dict a = {"CPU" : "Intel", "bus" : 64} ordered, changeable, no duplicate members bytes a = b"ABC" (store b'ABC' -- 65, 66, 67) a = bytes([1, 2, 3]) (store b'\x01\x02\x03' -- 1, 2, 3) a = bytes('好', 'UTF-8') (store b'\xe5\xa5\xbd' -- 229, 165, 189) the object cannot be modified bytearray a = bytearray(3) (store 0, 0, 0) a = bytearray([1,2,3]) (store b'\x01\x02\x03' -- 1, 2, 3) the object can be modified data type print(type(x)) str, list, tuple, set and dict are iterable objects.
Strings
Python string is an array of characters. carriage return + line feed (\r\n, 0D 0A, 13 10) Windows \r\n Unix/Linux \n Escape Characters \' \\ \r \n \t octal \ooo (\101 A) hex \xhh (\x41 A) s = "一" + '二' + "三" print(s[1]) 二 print(len(s)) 3 for x in s: print(x) 一 二 三 s = '''ABC 123''' print(len(s)) 7 a=bytes(s,"UTF-8") print(a) b'ABC\n123' for x in a: print(x) 65 66 67 10 49 50 51 Substring? s = "CPU HDD SSD" print("HDD" in s) True Slice b = "ABCDEFGHIJKL" s=b[2:5] CDE s=b[9:] JKL s=b[:3] ABC a=50 b=2 c=a*b s="{} * {} = {}" t=s.format(a,b,c) print(t) 50 * 2 = 100
Lists
indexed, changeable, allow duplicate values a=["CPU","HDD","SSD"] a=list(("a","b","c","d","e","f")) #Convert a tuple to a list i=len(a) a[0] the first item a[-1] the last item a[2:4] return a new list with a[2] and a[3] a[2:] a new list from a[2] to end a[:4] a new list from a[0] to a[3] a[2:4] = ["x","y"] update a[2] and a[3] x, y, *z = a unpack, x<--a[0], y<--a[1], z<--others a.insert(2, "q") a[2]="q" a.append("w") add to the end a.pop(2) remove a[2] a.pop remove the last item a.remove("x") remove the first item = "x" del a[2] remove a[2] del a remove the list, not exist a.clear() empty the list a=[] item in a True of False x = a.index("HDD") returns the index at the first occurrence x = a.count("HDD") counts the number of occurrences a.extend(b) iterable object b is added to the end of list a newlist = a + b join the lists b = a b is a reference to a b = a.copy() b is a copy of a b = list(a) b is a copy of a b = a*3 b is a copy of a+a+a a.reverse() a.sort() ascending, case sensitive by default a.sort(reverse = True) descending a.sort(key = str.lower) case insensitive #sort according to the return value of distance() def distance(x): return abs(x-100) a = [100, 120, 90, 80, 150] a.sort(key = distance) for x in a: print(x) for i in range(len(a)): print(a[i]) newlist = [expression for item in iterable if condition == True] newlist = [x.upper() for x in a if "CPU" in x.upper()] newlist = [x*2 for x in range(10)]
Tuples
ordered, allow duplicate values, cannot change, add or remove items a = ("CPU","HDD","SSD") a = ("CPU",) a tuple with only one item must be ended with a comma
Sets
unindexed, value unchangeable, no duplicate members a = {"CPU","HDD","SSD"} a = set(("CPU","HDD","SSD")) i=len(a) for x in a: print(x) a.add("RAM") add an item a.remove("CPU") remove an item (error check) a.discard("CPU") remove an item (no error check) del a remove the set, not exist a.clear() empty the set a={} item in a True or False a.isdisjoint(b) True or False a.issubset(b) True or False a is a subset of b a.issuperset(b) True or False a is a superset of b a.update(b) iterable object b is added to a c = a.union(b) return a new set from a and b a.intersection_update(b) a is updated to keep the intersection only c = a.intersection(b) return the intersection as a new set a.symmetric_difference_update(b) a is updated to keep the symmetric difference of a and b (items not present in both sets) c = a.symmetric_difference(b) return a new set a.difference_update(b) a is updated to keep the items that only in a but not in b c = a.difference(b) return a new set b = a b is a reference to a b = a.copy() b is a copy of a b = set(a) b is a copy of a
Dictionaries
ordered, changeable, no duplicate members store key:value pairs a = { "CPU": 900, "HDD": 350, "SSD": 400 } a = dict(CPU=900,HDD=350,SSD=400) k = ("CPU","HDD","SSD") keys v = 0 value for all keys. Optional,default=None a = dict.fromkeys(k, v) i=len(a) x = a["HDD"] x stores the value x = a.get("HDD") x stores the value x = a.keys() a stores a list of all the keys (gets updated,) x = a.values() a stores a list of all the values (gets updated, ) x = a.items() a stores each item as tuples in a list (gets updated, ) dict_items([('CPU', 900), ('HDD', 350), ('SSD', 400)]) a["HDD"] = 450 update a["LCD"] = 800 add a.update({"DVD drive": 200,"Keyboard":50,"Mouse":60}) a.update(b) dictionary b is added to a x = a.setdefault("RAM", 300) if "RAM exists, 300 is ignored, x=original value if not exist, "RAM":300 is added. x=300 a.pop("HDD") remove del a["HDD"] remove a.popitem() removes the last inserted item del a remove the dictionary, not exist a.clear() empty the dictionary a={} for x in a: print(x) x stores the key print(a[x]) for x in a.keys(): print(x) x stores the key print(a[x]) for x in a.values(): print(x) x stores the value for x, y in a.items(): print(x, y) x=key, y=value "HDD" in a True or False b = a b is a reference to a b = a.copy() b is a copy of a b = dict(a) b is a copy of a
Operators
assignment x = y = z = 0 a, b, c = "CPU", "HDD", "SSD" x, y, z = [1, 2, 3] += -= *= /= %= //= **= &= |= ^= >>= <<= arithmetic + - * / %(modulus) **(exp) //(floor division, -15//2 --> -8) bitwise & | ~(not) ^(XOR) << (push 0 in) >> (copy msb) comparison == != > < >= <= logical and or not membership in not in (x = [1,2,3,4,5], 2 in x --> True) identity is a is b --> a and b are the same object is not
Conditionals
if a > b: .... elif a == b: .... else: .... if a > b: print("a") if a > b: pass #nothing to do Conditional expression x = 2 if a > b else 1 print("a") if a > b else print("b") x = 3 if a > b else 2 if a == b else 1 print("a") if a > b else print("=") if a == b else print("b") Python does not have a switch or case statement.
Loops
while ....: .... if ....: continue #next .... if ....: break #exit the loop (the else part is not executed) else: print("normal exit from the loop") To implement a post-test loop while True: ....loop body.... if ....: break loop = True while loop: ....loop body.... loop = .... for loop iterates over a sequence(list tuple range dictionary set string) for x in a: .... if ....: continue #next .... if ....: break #exit the loop (the else part is not executed) else: print("normal exit from the loop") #x=last value in a * normal exit --> x=last value in a pass = an empty loop body Optimization: in this case, while loop is better than for loop for x in range(0, 30000): print(x) * at the end, x=29999 x = 0 while x < 30000: print(x) x += 1 * at the end, x=30000
Functions
def f(parameter): print("CPU") f(argument) def f(*p): #arbitrary arguments print(p[3]) #11 print(type(p)) #f(1,5,9,11,"a","b","c") def f(p1,p2,p3): print(p3) #['i', 'j'] f(p3=["i","j"],p1=4,p2="a") #keyword arguments
Reserved Words
and as assert break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield
Built-in Functions
Built-in Functions
abs() aiter() all() any() anext() ascii() bin() bool() breakpoint() bytearray() bytes() callable() chr() classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() eval() exec() filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() input() int() isinstance() issubclass() iter() len() list() locals() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() repr() reversed() round() set() setattr() slice() sorted() staticmethod() str() sum() super() tuple() type() vars() zip() __import__()
Styles
Style Guide for Python Code
Use UTF-8. Names are case sensitive. Function and variable names -- lowercase with _ separating words. Constants -- uppercase with _ separating words, usually defined on a module level. '' and "" strings are the same. 4 spaces per indentation level is preferred over TAB. Limit all lines to a maximum of 79 characters. # Comments are limited to 72 characters. Block comments generally apply to code that follows them, and are indented to the same level as that code. Surround = += -= == < > != <> <= >= in not in is is not and or with a single space on either side. If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Never use more than one space. Always have the same amount of whitespace on both sides of a binary operator. n,a,b = 1,2,3 n = n + 1 n += 1 n = a*2 + 3 n = a*a + b*b n = (a+b) / (a-b) Use a backslash \ for line continuation. Preferred ways of wrapping long lines: Aligned with opening delimiter. Break before the operator. total_mark = (chinese*3 + english*3 + maths*2 + ict + physics) Hanging indents should add a level. total_mark = ( chinese*3 + english*3 + maths*2 + ict + physics) print(total_mark) if (chinese>=50 and english>=50): print("OK")