Set and mapping types (unordered):
set {'Fred', 'John'} set(('Fred', 'John'))
Function with optional arguments:
def multiply(x, y=2): multiply(3) == 6 Python
cheat sheet
frozenset frozenset(('Fred', 'John')) return x * y multiply(3, 5) == 15
dict {'Fred': 123, 42: 'John'} multiply(3, y=5) == 15
dict([('Fred', 123), (42, 'John')])
dict(Fred=123, John=42)
Classes
Immutable set methods and operations: Code structure
intersection() symmetric_difference() issubset() Simple class definition with attributes and constructor:
union() copy() issuperset() class Simple: obj = Simple(7) Grouping: Whitespace has meaning. Line breaks separate
difference() isdisjoint() x = None obj.x == 7 statements, indentation creates logical blocks. Comments
def __init__(self, x): run from # to line break. Functional units go into modules
{1, 2} & {2, 3} == {2} {1, 2} == {2, 1} self.x = x (files) and packages (directories); each source file imports
{1, 2} | {2, 3} == {1, 2, 3} {1} < {1, 2} any modules it uses:
{1, 2} - {2, 3} == {1} {1, 2} <= {1, 2} Subclass which accesses a method of its Superclass: import math
{1, 2} ^ {2, 3} == {1, 3} class XY(Simple): obj = XY(7, 9) for x in range(0, (4+1)*2): # numbers 0 <= x < 10
y = None obj.x == 7 y = math.sqrt(x)
Set mutation methods: def __init__(self, x, y): obj.y == 9 print('The square root of {} is {}'.format(
add() update() intersection_update() super().__init__(x) x, y))
pop() remove() difference_update() self.y = y
clear() discard() symmetric_difference_update() Variable names: May contain letters (unicode, case-sensi-
Class with a method that can be called on instances: tive), numerals and _.
Mapping methods and operations: class CalcZ(XY): obj = CalcZ(7, 9)
get() keys() pop() copy() def do_z(self): obj.do_z() == 63
setdefault() values() popitem() fromkeys() return self.x * self.y Logic and flow control
update() items() clear()
Class with an automatically computed attribute: Conditions: compound statement or expression:
x = {'a': 1, 'b': 2}; x['d'] = 5 class AutoZ(XY): obj = AutoZ(7, 9) if x < y: print('equal'
'b' in x == True; x['a'] == 1; del x['b'] @property obj.z == 63 print(x) if x == y
def z(self): elif x > y: else 'unequal')
List and dict comprehensions: return self.x * self.y print(y)
[2 * i for i in range(3)] == [0, 2, 4] else:
{i: i ** 2 for i in range(3)} print('equal')
== {0: 0, 1: 1, 2: 4} This cheat sheet refers to Python 3.7:
https://docs.python.org/3.7/ Iteration: over sets or until termination:
for name in ['John', 'Fred', 'Bob']:
Functions Coding style conventions according to PEP8 if name.startswith('F'):
https://python.org/dev/peps/pep-0008/ continue
Simple function definition, takes an argument of any type: print(name)
def double(x): double(2) == 4 Text by Kristian Rother, Thomas Lotze (CC-BY-SA 4.0)
return x * 2 double('abc') == 'abcabc' while input('Stop?') != 'stop':
https://www.cusy.io/de/seminare if 'x' in input('Do not type an x.'):
Function that does not explicitly return a value: print('You typed an x.')
def idle(): pass idle() == None break
else:
print('Loop finished without typing an x.')
Exceptions: for explicit error handling: Data types String methods:
try: upper() casefold() title()
if 'x' in input('Do not type an x.'): Numeric types: lower() swapcase() capitalize()
raise RuntimeError('You typed an x.') int 137 -42 1_234_567 0b1011 0o177 0x3f
except Exception as exc: float 2.71 .001 2.718_281 5.43e-10 center() ljust() rjust()
print(exc) complex 0.3j 5J (1 - 2.5j) lstrip() rstrip() strip()
else:
print('You did not type an x.') int(1) int('2_345') int('0xff') int(' 1 ') count() index() rindex() find() rfind()
finally: float(12) float('2.71') float('1.4e9')
print('Good bye.') complex('5j') complex(1, -2.3) join() partition() rpartition()
str(123.0) == '123.0'; bin(23) oct(23) hex(23) split() rsplit() splitlines()
Context managers: implicit error handling for resources:
with open('story.txt', 'w') as story: Numeric operations: replace() format() translate() expandtabs()
print('Once upon a time...', file=story) 1 + 1 == 2; 7 / 2 == 3.5; 7 // 2 == 3; 7 % 2 == 1 zfill() format_map() maketrans()
2 - 1 == 1; 2 * 3 == 6; divmod(7, 2) == (3, 1)
2 ** 3 == 8; (1 + 3j).conjugate() == 1 - 3j isdigit() isdecimal() isupper() startswith()
Built-in functions pow(2, 3) == 8; abs(-1) == 1; round(1.5) == 2 isalpha() isnumeric() islower() endswith()
isalnum() isprintable() istitle()
Input and output: Boolean type (truth values): isspace() isidentifier()
input([prompt]) open(file, ...) bool True False
print(*objects, file=sys.stdout, ...) bool(123) == True; bool(0) == False Sequence types:
tuple () (1,) (1, 'abc', 3.4)
Collections: Boolean operations: list [] [1] [1.0, 'abc', [1, 2, 3]]
iter(obj[, sentinel]) next(iterator) True and False == False; True or False == True range tuple(range(1, 4)) == (1, 2, 3)
all(iterable) filter(function, iterable) not True == False; not 42 == False; 0 or 42 == 42
any(iterable) map(function, *iterables) list('ab') == ['a', 'b']; tuple([1, 2]) == (1, 2)
max(iterable) reversed(sequence) Text (unicode) strings: (1, 1, 2).count(1) == 2; (1, 2, 3).index(3) == 2
min(iterable) sorted(iterable, ...) str 'abc' """abc""" """some
len(sequence) enumerate(iterable) "a'b'c" 'a\'b\'c' multiline Sequence and string operations, slicing:
sum(iterable[, start]) zip(*iterables) 'äbc' 'a\xfcc' 'ab\nc' string""" 'ab' * 3 == 'ababab'; [1, 2] in [0, 1, 2] == False
'ab' + 'cd' == 'abcd'; 'bc' in 'abcd' == True
Object representation: ord('A') == 65; chr(65) == 'A' (1, 2) + (3,) == (1, 2, 3); 1 in (0, 1) == True
ascii(obj) format(obj[, format_spec]) 'äbc'.encode('utf-8') == b'\xc3\xa4bc'
repr(obj) 'abc'[1] == 'b'; (1, 2, 3)[-1] == 3
String formatting: 'abcd'[1:3] == 'bc'; [1, 2][:] == [1, 2]
Object manipulation and reflection: 'Mr {name}: {age} years old.'.format( 'abcd'[1:] == 'bcd'; [1, 2][:] is not [1, 2]
dir([obj]) isinstance(obj, classinfo) name='Doe', age=42) == 'Mr Doe: 42 years old.' 'abcdefgh'[1:7:2] == 'bdf'
vars([obj]) issubclass(class, classinfo)
hasattr(obj, name) setattr(obj, name, value) name = 'Doe'; age = 42 List mutation methods and operations:
getattr(obj, name) delattr(obj, name) f'Mr {name}: {age} years' == 'Mr Doe: 42 years' append() pop() copy() sort() extend()
insert() remove() clear() reverse()
x = [1, 2]; x += [3]; x *= 2; del x[4]
del x[1:3]; x[:2] = [4, 5, 6]