Skip to content
BetaDE

Quick reference

Python cheat sheet

Everything important on one page. Tip: press Ctrl+P (Mac: ⌘+P) to print it.

Output & variables→

print("Hallo")
Print text
x = 5
Store a value in a variable
f"{name} ist {alter}"
f-string: put variables into text
name = input("Name? ")
Read input (always text!)
int("12") float("2.5") str(7)
Convert type

Maths & comparing

+ - * /
Basic arithmetic
// % **
floor division · remainder · power
== != < > <= >=
Comparisons → True/False
and or not
Combine conditions
x += 1
Increase x by 1

Decisions→

if x > 10: ... elif x > 5: ... else: ...
The first matching branch runs

Loops→

for i in range(5):
0, 1, 2, 3, 4
range(1, 10, 2)
start, end (excluded), step
while x < 100:
Repeat while true
break continue
Leave loop · next round
for i, w in enumerate(items):
Loop with a counter

Lists→

l = [3, 1, 2]
Create a list
l[0] l[-1] l[1:3]
first · last · slice
l.append(4) l.remove(1) l.pop()
append · remove · take out the last
len(l) sum(l) max(l) min(l)
length · sum · largest · smallest
sorted(l) 3 in l
sorted · contained?

Strings→

s.upper() s.lower() s.strip()
upper · lower · trim spaces
s.replace("a", "b") s.split(",")
replace · split
"-".join(items)
join a list into text
s[::-1] len(s) s.count('e')
reversed · length · count

Dictionaries→

d = {"Mia": 2, "Ben": 1}
key: value
d["Mia"] d.get("Tom", 0)
look up · look up safely
d["Lea"] = 3
add or change
for k, v in d.items():
go through all pairs

Functions→

def f(x, y=2): return x * y
Function with a default value
f(3) f(3, 5)
call it
lambda x: x * 2
One-line mini function

Handling errors→

try: ... except ValueError: ...
Catch errors instead of crashing
assert x > 0, 'Text'
Check – otherwise AssertionError

Files & modules→

with open("a.txt", "w") as f: f.write("Hi\n")
write ('a' = append)
for line in open("a.txt"):
read line by line
import math from random import randint
import modules

Classes→

class Robo: def __init__(self, name): self.name = name def hello(self): return self.name
Blueprint with attribute and method
r = Robo("R2") r.hello()
Build and use an object

Pro→

[x * 2 for x in l if x > 0]
List comprehension with filter
{k: len(k) for k in words}
Dictionary comprehension
def gen(): yield 1
Generator
@decorator def f(): ...
Extend a function
def f(x: int) -> str:
Type hints
async def f(): await asyncio.sleep(1)
Coroutine

Pybricks (LEGO SPIKE)

hub = PrimeHub()
create the hub
hub.light.on(Color.RED) hub.display.text("Hi")
light · scrolling text
drive_base = DriveBase(l, r, wheel_diameter=56, axle_track=114)
two motors as a drive base
drive_base.straight(200) drive_base.turn(90)
drive (mm) · turn (degrees)
sensor.distance() color.reflection()
distance in mm · brightness 0–100
wait(500)
wait 500 ms