if 2*x < y or x > 2*y: # if, elif, else as usual Control
print("far") # no braces but indents
Python Cheat Sheet by Roger Wattenhofer
elif x == y:
print("equal")
else:
print("near")
a = 10 // 3 # a = 3 (integer division) Math for item in d: # traverse keys (also: list, set)
b = 10 % 3 # b = 1 (remainder of division)
for i in range(len(d)): # traverse over indexes
c = 10 / 3 # c = 3.3333333333333335 (automatic float)
for i, item in enumerate(d): # both index and item
d = (3 * 0.1) == 0.3 # d = False (floats are not exact!)
break # break current loop
e = 2 ** 1000 # (power results in big number? no problem!)
1 + 1 # → 2 (interactive: use _ for last result)
while x > 3: # while loops as usual
print(x)
s = 'abcdefgh' Strings & Lists x -= 1 # x = x - 1
a = len(s) # a = 8
b = s[0] # b = 'a'
print("hello") if x == 5 else print("x =",x) # cond. expression
c = s[-1] # c = 'h'
d = s[1:3] # d = 'bc' (slicing)
e = s[3:-1] # e = 'defg' def square(x): # function definition Functions
f = s[3:-1:2] # f = 'df' return x*x # with return value
g = s[::-1] # g = 'hgfedcba'
f = lambda x : x*x # lambda is one line function
x = list(range(5)) # x = [0, 1, 2, 3, 4] (range: lazy) print(f(5)) # → 25
y = [3, 5, 8] # y = [3, 5, 8] (direct construction) l = [i*i for i in range(1,6)]
z = [i*i for i in range(1,6)] # z = [1, 4, 9, 16, 25] (list compr.) l.sort(key=lambda v : v % 10) # l = [1, 4, 25, 16, 9]
z.append(77) # (appending element to list)
z.extend([88,99]) # (extending list with another list)
x = y = z = 1 # globally: set all = 1 Scope
s = set({2,1,3,2,1}) Sets & Dictionaries def foo():
s.add(4); s.remove(2) # s = {1, 3, 4} global x # keyword global: global x is used
print(3 in s) # → True x, y = 2, 2 # x is global, y is local, z is unchanged
print(x,y,z) # → 2 2 1 (z is accessible)
d = {'alice': 24, 'bob': 22, 'charlie': 23} # (dictionary)
d['eve'] = 26 # (add or change entry) foo()
v = d.pop('charlie',None) # v = 23 (remove) print(x,y,z) # → 2 1 1 (note that global y was unchanged)
def next_few(x, number = 3): # default = 3 Parameters old = [1,[2,3]] Copy
res = [] same = old
for y in range(number): shallow = old.copy() # copying basic elements, referencing lists
res.append(x+y) import copy # deepcopy method must be imported
return res deep = copy.deepcopy(old) # copying recursively
same[0] = 'a'
print(next_few(3)) # → [3, 4, 5] old[1][1] = 'c'
first, *middle, last = next_few(3,5) # middle = [4, 5, 6], last = 7 print('old =', old) # → ['a', [2, 'c']]
print('same =', same) # → ['a', [2, 'c']]
def foo(var, *args, **d_args): print('shallow =', shallow) # → [1, [2, 'c']]
print(var) # var is any type print('deep =', deep) # → [1, [2, 3]]
print("args =", args) # *args is an arbitrary list
print("d_args =", d_args) # **d_args is a dictionary def foo(v, l): # beware: changing lists in functions
v += 1
foo(1, 2, 3, x=4, y=5) # args = (2,3), d_args = {'x': 4, 'y': 5} l[1] = 'x'
x = 5
b = True # boolean variables More Types ll = [1,2]
bb = not b # bb = False
foo(x,ll)
c = 2+3j # complex numbers
print("function:", x, ll) # → 5 [1, 'x']
cc = c-2 # cc = 3j
t = (2,3) # tuple, like a list but immutable
d = {t: True, c: False} # keys cannot be lists (tuples okay)
s = str(c) # s = '(2+3j)' (conversion example)
class Foo: Object Oriented
def __init__(self, name): # constructor
self.name = name
def printName(self): # method (self = always first argument)
print('I am', self.name)
bar = Foo('bar') # new object (constructor with name)
bar.printName() # → I am bar