Python cheatsheet – syntax overview
58 key commands and patterns for quick reference.
Basics Operators Control flow Lists Dictionaries & Sets Strings Functions & Classes Files & Errors Handy helpers
Basics
print("Text", variable) | Output to the console |
x = input("Input: ") | Read input as a string |
# Comment | Single-line comment |
type(x) | Determine the type of a value |
int("5") float("2.5") str(5) | Type conversion |
f"Hello {name}!" | f-string: insert values into text |
x, y = y, x | Swap values |
Operators
+ - * / // % ** | Arithmetic: division, integer division, remainder, power |
== != < > <= >= | Comparisons |
and or not | Logical operators |
x in liste | Check membership |
a is b | Identity (same object?) |
x += 1 | Assignment with operation |
Control flow
if x > 0:
elif x == 0:
else: | Branching |
for i in range(5): | Loop over 0..4 |
for i, x in enumerate(liste): | Index and value |
while bedingung: | Loop with a condition |
break / continue | Exit the loop / next iteration |
match x:
case 1: ...
case _: ... | Pattern matching (Python 3.10+) |
Lists
l = [1, 2, 3] | Create a list |
l.append(4) l.extend([5, 6]) | Append |
l.insert(0, "x") | Insert at a position |
l.remove(3) l.pop() del l[0] | Remove |
l[1:3] l[::-1] l[-1] | Slicing, reversing, last element |
sorted(l) l.sort() l.reverse() | Sort (new list / in place) |
len(l) sum(l) min(l) max(l) | Length, sum, minimum, maximum |
[x*2 for x in l if x > 1] | List comprehension |
Dictionaries & Sets
d = {"a": 1} | Create a dictionary |
d["b"] = 2 d.get("c", 0) | Set / read with a default value |
d.keys() d.values() d.items() | Keys, values, pairs |
del d["a"] d.pop("b") | Remove an entry |
{**d1, **d2} d1 | d2 | Merge dictionaries |
s = {1, 2, 3} s & t s | t s - t | Set: intersection, union, difference |
Strings
s.upper() s.lower() s.title() | Upper/lower case |
s.strip() s.lstrip() s.rstrip() | Remove whitespace |
s.split(",") ",".join(liste) | Split / join |
s.replace("a", "b") | Replace |
s.startswith("x") s.endswith("y") | Check start/end |
s.find("x") s.count("x") | Search / count |
"{:>8.2f}".format(3.14159) | Formatting (right-aligned, 2 decimal places) |
Functions & Classes
def f(a, b=2, *args, **kwargs): | Function with a default value and catch-all parameters |
lambda x: x + 1 | Anonymous function |
class A(Basis):
def __init__(self): | Class with inheritance and constructor |
@staticmethod @classmethod @property | Important decorators in classes |
isinstance(x, int) | Check type |
super().__init__() | Constructor of the base class |
Files & Errors
with open("f.txt") as f: | Open a file safely |
f.read() f.readlines() f.write("x") | Read / write |
try: ... except ExceptionType as e: ... finally: ... | Error handling |
raise ValueError("Text") | Raise an error |
from pathlib import Path
Path("a") / "b.txt" | Platform-independent paths |
import os
os.listdir(".") | List the files in a folder |
Handy helpers
zip(a, b) | Iterate over two lists in pairs |
map(f, l) filter(f, l) | Apply a function / filter |
any(l) all(l) | At least one / all elements true |
range(start, stop, step) | Generate a number sequence |
import random
random.randint(1, 6) | Random number |
help(objekt) dir(objekt) | Help and available attributes |