Pingu
Computer MySQL PostgreSQL Books Publications
Spielereien Kanu Geopolitik Business TopoDB POI Klettersteigen History TransPool Thermal Baden Brokenstuben Goldwaschen
Blog Contact
Shinguz
Google
/ch/open

Meine Python Notizen

/ home / computer

Cheat sheets

Getting started

$ sudo apt install python-is-python3
$ ll /usr/bin/python /usr/bin/python3
lrwxrwxrwx 1 root root  7 Apr  9  2025 /usr/bin/python -> python3
lrwxrwxrwx 1 root root 10 Jun 30  2025 /usr/bin/python3 -> python3.13
$ python --version
Python 3.13.5
$ python
>>> exit()   # or ^D
$ python example.py
$ python -i example.py   # interactive

Comments

# This is a comment
# print("This code will not run.")
print("This will run.")   # Comments are ignored by Python

'''
This is a multiline
comment.
'''

"""
This is a documentation
string.
""""

# This is a multiline
# comment according to PEP8.

Simple data types and Variable Type Hinting

age: int = 25
name: str = "Alice"
height: float = 5.9
is_student: bool = True
unknown = None
x, y = 10, 20   # Assign multiple values
a = b = c = 0   # Give same value to multiple variables

type(var)
isinstance(3.14, float)   # True
isinstance(42, str)   # False
issubclass(int, object)   # True - everything inherits from object
issubclass(int, float)   # False

Strings Creation, Operations and Methods

single = ‘Hello’ double = “World” multi = “““Multiple line string”””

greeting = “me” + “ow!” # “meow!” repeat = “Meow!” * 3 # “Meow!Meow!Meow!” length = len(“Python”) # 6

“a”.upper() # “A” “A”.lower() # “a” " a “.strip() # “a” “abc”.replace(“bc”, “ha”) # “aha” “a b”.split() # [“a”, “b”] “-".join([“a”, “b”]) # “a-b”

text = “Python” text[0] # “P” (first) text[-1] # “n” (last) text[1:4] # “yth” (slice) text[:3] # “Pyt” (from start) text[3:] # “hon” (to end) text[::2] # “Pto” (every 2nd) text[::-1] # “nohtyP” (reverse)

f-strings

name = “Aubrey” age = 2 f"Hello, {name}!” # “Hello, Aubrey!” f”{name} is {age} years old" # “Aubrey is 2 years old” f"Debug: {age=}" # “Debug: age=2”

Format method

template = “Hello, {name}! You’re {age}.” template.format(name=“Aubrey”, age=2) # “Hello, Aubrey! You’re 2.”

Normal string with an escaped tab

“This is:\tCool.” # “This is: Cool.”

Raw string with escape sequences

r"This is:\tCool." # “This is:\tCool.”

Numbers & Math

10 + 3 # 13 10 - 3 # 7 10 * 3 # 30 10 / 3 # 3.3333333333333335 10 // 3 # 3 10 % 3 # 1 2 ** 3 # 8

abs(-5) # 5 round(3.7) # 4 round(3.14159, 2) # 3.14 min(3, 1, 2) # 1 max(3, 1, 2) # 3 sum([1, 2, 3]) # 6

Complex Data Types (Collections)

List

empty = []
fruits = ["banana", "apple", "orange"]
numbers = [1, 3, 2]
mixed = [1, "two", 3.0, True]
print(mixed)

for fruit in fruits:
  print(fruit)

numbers.append(42)        # Add to end: [1, 3, 2, 42]
numbers.insert(0, 9)      # Insert at index 0: [9, 1, 3, 2, 42]
numbers.extend([17, 5])   # Extend with iterable at the end: [9, 1, 3, 2, 42, 17, 5]
numbers.remove(3)         # Remove first occurence of value 3: [9, 1, 2, 42, 17, 5]
del numbers[3]            # Removes element with index 3: [9, 1, 2, 17, 5]
last = numbers.pop()      # Pop returns last element: [9, 1, 2, 17], last: 5
numbers.index(17)         # Index of first element with the specified value: 3
numbers.reverse()         # Reverse the elements of the list in place: [17, 2, 1, 9]
numbers.sort()            # Sort the items of the list in place: [1, 2, 9, 17]
numbers.count(2)          # Return the number of times value appears in the list: 1
copy = numbers.copy()     # Returns a copy of the list: [1, 2, 9, 17], copy: [1, 2, 9, 17]
numbers.clear()           # Removes all the elements from the list: []

fruits = ["banana", "apple", "orange"]
fruits[0]                 # "banana"
fruits[-1]                # "orange"
"apple" in fruits         # True
len(fruits)               # 3

Tuple

empty = ()
point = (3, 4)
single = (1,)    # Note the comma!

fruitstuple = "apple", "banana", "cherry"
fruitstuple      # ('apple', 'banana', 'cherry')

x, y = point
x                # 3
y                # 4

first, *rest = (1, 2, 3, 4)
first            # 1
rest             # [2, 3, 4], List!

point.count(4)   # 1
point.index(3)   # 0

v = ([1, 2, 3], [3, 2, 1])

Dictionary

empty = {}
user = {"id": 1, "name": "Oli", "gender": "male"}

user["age"] = 42           # Add key and value: {'id': 1, 'name': 'Oli', 'gender': 'male', 'age': 42}
user["name"] = "Oliver"    # Update value: {'id': 1, 'name': 'Oliver', 'gender': 'male', 'age': 42}
age = user.get("age", 0)   # Get with default: age: 42
del user["gender"]         # Delete key with value: {'id': 1, 'name': 'Oliver', 'age': 42}
age = user.pop("age")      # Returns age and removes it from dictionary: {'id': 1, 'name': 'Oliver'}, age: 42

user.keys()                # dict_keys(['id', 'name'])
user.values()              # dict_values([1, 'Oliver'])
user.items()               # dict_items([('id', 1), ('name', 'Oliver')])

Set

myset = set()            # set()
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)          # {'orange', 'banana', 'pear', 'apple'}
'orange' in basket     # True

numbersA = {1, 2, 3}   # {1, 2, 3}

a = set('abracadabra')   # {'r', 'c', 'b', 'd', 'a'}
b = set('alacazam')      # {'c', 'a', 'l', 'z', 'm'}

a | b            # In a OR b: {'r', 'c', 'b', 'd', 'a', 'z', 'l', 'm'}
a & b            # In a AND b: {'a', 'c'}
a - b            # In a but NOT in b: {'d', 'r', 'b'}
a ^ b            # In a OR b but NOT in both: {'l', 'r', 'b', 'z', 'd', 'm'}

Conditionals

  • Python uses indentation for code blocks

if age < 13: category = “child” elif age < 20: category = “teenager” else: category = “adult”

x == y # Equal to x != y # Not equal to x < y # Less than x <= y # Less than or equal x > y # Greater than x >= y # Greater than or equal

if age >= 18 and has_car: print(“Roadtrip!”)

if is_weekend or is_holiday: print(“No work today.”)

if not is_raining: print(“You can go outside.”)

Switch case in Python (since 3.10):

value = 2

match value: case 1: result = “one” case 2: result = “two” case 3: result = “three” case _: result = “unknown”

print(result)

point = (3, 4) match point: case (x,): print(f"1D point at {x}") case (x, y): print(f"2D point at ({x}, {y})") case (x, y, z): print(f"3D point at ({x}, {y}, {z})")

Loops

Loop through range

for i in range(5): # 0, 1, 2, 3, 4 print(i)

Loop through collection

fruits = [“apple”, “banana”] for fruit in fruits: print(fruit)

With enumerate for index

for i, fruit in enumerate(fruits): print(f"{i}: {fruit}")

while True: user_input = input(“Enter ‘quit’ to exit: “) if user_input == “quit”: break print(f"You entered: {user_input}”)

for i in range(10): if i == 3: continue # Skip this iteration if i == 7: break # Exit loop print(i)

Augmented Assignments

counter: int = 0 counter += 1 numbers += [4, 5] permissions |= write

Functions

def greet(): return “Hello!”

def greet_person(name): return f"Hello, {name}!”

def add(x, y=10): # Default parameter return x + y

Function Type Hinting

def greet(name: str) -> str:
    return f"Hello, {name}"

Static Type Checking with mypy

To enforce type hints, use mypy. Install it via pip:

$ pip install mypy
$ mypy example.py