Understanding Python Terms
Variable, Dictionary, List Comprehension, Decorator — sounds like gibberish? It's not. This lexicon explains all important Python terms so everyone can understand them. No prior knowledge needed.
Each term contains a short definition, a detailed explanation, an everyday analogy, and a concrete code example — for different learning styles.
The Most Important Terms
These 8 terms form the foundation for everything else. They are the basis on which you will understand all other concepts.
What Does This Mean in Practice?
Variables store data under a name. You create them with name = value. Python automatically recognizes whether it's text, numbers, or booleans — you don't need to declare the type beforehand (unlike Java or C).
The Analogy
Imagine a chest of drawers. On one it says "favorite_color", and inside is "Blue". On another it says "age" with "16". Variables work exactly like this: name on the drawer, value inside.
Why Is This Important?
Without variables, you couldn't store, process, or reuse data. Every calculation, every username, every result ends up in a variable. They are the beginning of everything.
Example
name = "Lisa"
alter = 16
print(f"Hello {name}, du bist {alter} Jahre alt.")
What Does a Function Do?
You define a function with def name():. Everything indented below belongs to the function. You can pass values to it (parameters) and it can return a result (return).
The Analogy
A function is like a recipe in a cookbook. You write it down once: "Take 2 eggs, crack them, stir...". Every time you want an omelet, you call up the recipe — you don't have to reinvent it each time.
Why Is This Important?
Functions are the heart of clean code. They prevent copy-paste, make programs clearer, and make testing easier. In Python, almost all commands are actually functions — print(), len(), input().
Example
def begruessung(name):
return f"Hello {name}!"
print(begruessung("Max"))
print(begruessung("Lisa"))
What Can You Do with Lists?
You create lists with square brackets: [1, 2, 3]. You access them by index: list[0] gives the first element. With append(), remove(), sort() you modify the list. Lists are mutable.
The Analogy
A list is like a shopping list on paper. You can add points, cross them out, reorder them — the order is preserved. Unlike a set, where order doesn't matter.
Why Is This Important?
Lists are the most commonly used data structure in Python. They store users, products, high scores, lines from a file — almost anything with multiple elements ends up in a list.
Example
noten = [4.5, 5.0, 3.5, 5.5]
noten.append(5.0)
durchschnitt = sum(noten) / len(noten)
print(f"Durchschnitt: {durchschnitt}")
How Does It Work?
if checks a condition. If it's true, the indented block is executed. elif (else if) checks an alternative. else catches all other cases. Don't forget the colon :!
The Analogy
A traffic light: When red → stop. When yellow → prepare. When green → go. That's exactly how conditions work: The program looks at what currently applies and acts accordingly.
Why Is This Important?
Without conditions, programs would be rigid and predictable. If/else enables real decisions: Is the user old enough? Is the password correct? Is the game over? Almost every program needs conditions.
Example
alter = 15
if alter >= 16:
print("Du darfst Moped fahren")
elif alter >= 14:
print("Fast! Noch 2 Jahre")
else:
print("Geduld ist eine Tugend")
How Does It Work?
for element in collection: takes each element of the collection and executes the code block with it. With range(5) you count from 0 to 4. Indentation determines what belongs to the loop.
The Analogy
A teacher going through a class list and giving each student a grade. They don't say "Student 1, then Student 2..." — they simply go through the list. That's exactly what the for loop does.
Why Is This Important?
Loops save endless amounts of code. Instead of writing print() 100 times, you write a loop. They are essential for lists, files, game loops, and data processing.
Example
namen = ["Anna", "Ben", "Clara"]
for name in namen:
print(f"Hello {name}!")
for i in range(3):
print(f"Round {i+1}")
What Does a Dictionary Do?
You create it with curly braces: {"name": "Max", "age": 16}. With dict["name"] you retrieve the value. You can add, change, and delete key-value pairs. Keys must be unique.
The Analogy
A real dictionary: You look up a word (key) and find the meaning (value). You don't search for page 247, but for the word itself. That's the crucial difference from a list.
Why Is This Important?
Dictionaries are perfect for structured data: user profiles, configurations, JSON APIs, quiz answers. They make code more readable because you write user["email"] instead of data[3].
Example
nutzer = {
"name": "Lisa",
"alter": 17,
"stadt": "Wien"
}
print(f"{nutzer['name']} wohnt in {nutzer['stadt']}")
What Is OOP?
Object-oriented programming (OOP) packages data and functions together. class Dog: defines the blueprint. __init__ is the constructor that gets called when creating. self refers to the current object.
The Analogy
A class is like the blueprint of a house. The blueprint says: 3 rooms, kitchen, bathroom. But you don't live in the blueprint — you build concrete houses from it. Each house (object) has its own colors, residents, address.
Why Is This Important?
OOP helps structure complex programs. PyBuddy is an object. A player in the game is an object. Without classes, you would manually link data and functions — chaotic and error-prone.
Example
class Hund:
def __init__(self, name):
self.name = name
def bellen(self):
return f"{self.name} sagt: Wuff!"
bello = Hund("Bello")
print(bello.bellen())
f before the quotation marks. You can directly embed variables and expressions in curly braces — elegant, readable, and fast.
How Does It Work?
Instead of "Hello " + name you write f"Hello {name}". In the curly braces you can also use expressions: f"Sum: {a + b}". You can even specify formatting: f"{price:.2f} €" for 2 decimal places.
The Analogy
An f-string is like a fill-in-the-blank template: "Hello [NAME], you are [AGE] years old." You fill in the blanks automatically — instead of piecing the text together bit by bit.
Why Is This Important?
f-strings are the modern, recommended way to format strings in Python. They are faster than .format() and more readable than string concatenation with +. You will see them in almost every Python program.
Example
name = "Max"
alter = 16
print(f"Hello {name}!")
print(f"Next year you will be {alter + 1}")
print(f"{name:*^10}") # ***Max***
A 2 Terms
Argument
A value you pass to a function. print("Hello") — "Hello" is the argument. Functions can take any number of arguments.
def begruessen(name):
print(f"Hello {name}!")
begruessen("Max") # "Max" is the argumentAttribut
A variable that belongs to an object. In a class, attributes are the object's data: self.name = "Max" — name is an attribute.
class Hund:
def __init__(self, name):
self.name = name # Attribute
bello = Hund("Bello")
print(bello.name) # "Bello"B 3 Terms
Bool / Boolean
A boolean value: either True or False. Essential for conditions and comparisons. Everything in Python is "truthy" or "falsy".
ist_aktiv = True
hat_geld = False
if ist_aktiv and not hat_geld:
print("Aktiv, aber pleite")
print(bool(0)) # False
print(bool("Hello")) # Truebreak
Breaks a loop immediately. When a condition is met, Python jumps out of the loop — useful for searches and early exits.
for i in range(10):
if i == 5:
break # End loop
print(i)
# Output: 0, 1, 2, 3, 4Built-in Funktion
A function that Python provides out of the box: print(), len(), input(), range(), type() — available without import.
text = "Hello World"
print(len(text)) # 10
print(type(text))
print(max(3, 7, 2)) # 7
print(sum([1,2,3])) # 6C 3 Terms
class
Defines a blueprint for objects. With class Dog: you create a template from which you can generate any number of dog objects. Basis of object orientation.
class Katze:
def __init__(self, name):
self.name = name
def miauen(self):
return f"{self.name} sagt Miau!"
mimi = Katze("Mimi")
print(mimi.miauen())continue
Skips the rest of the current loop round and immediately starts the next one. Unlike break, the loop doesn't completely abort.
for i in range(1, 6):
if i == 3:
continue # Skip 3
print(i)
# Output: 1, 2, 4, 5Comprehension
Compact syntax for lists, dictionaries, and sets: [x*2 for x in list] — elegant, fast, and pythonic. One line instead of several.
zahlen = [1, 2, 3, 4, 5]
quadrate = [x**2 for x in zahlen]
gerade = [x for x in zahlen if x % 2 == 0]
print(quadrate) # [1, 4, 9, 16, 25]
print(gerade) # [2, 4]D 4 Terms
Decorator (@)
A function that "wraps" and extends another function. @staticmethod or custom decorators — an advanced concept for clean code.
import time
def timer(func):
def wrapper(*args):
start = time.time()
result = func(*args)
print(f"Dauer: {time.time()-start:.4f}s")
return result
return wrapper
@timer
def langsame_funktion():
time.sleep(1)Dictionary (dict)
Stores key-value pairs: {"name": "Max", "age": 16}. Fast access via the key. Perfect for structured data and JSON.
nutzer = {
"name": "Lisa",
"alter": 17,
"stadt": "Wien"
}
print(nutzer["name"])
nutzer["email"] = "lisa@mail.at"
print(nutzer.get("telefon", "Nicht angegeben"))Docstring
A documentation string directly under a function or class. With triple quotes: """Description""". Displayed by tools like help().
def flaeche(breite, hoehe):
"""Berechnet die Flaeche.
Args:
breite: Breite in cm
hoehe: Hoehe in cm
Returns:
Flaeche in cm2
"""
return breite * hoeheDunder / Magic Method
Methods with double underscores: __init__, __str__, __len__. They define how objects behave — e.g. what happens when you call print(object).
class Buch:
def __init__(self, titel):
self.titel = titel
def __str__(self):
return f"Buch: {self.titel}"
def __len__(self):
return len(self.titel)
b = Buch("Python")
print(str(b)) # Buch: Python
print(len(b)) # 6E 4 Terms
elif
"Else if" — Checks another condition when the if was false. You can use as many elifs as you want to cover multiple cases.
note = 2
if note == 1:
print("Sehr gut!")
elif note == 2:
print("Gut!")
elif note == 3:
print("Befriedigend")
else:
print("Mehr Uebung noetig")else
Catches all cases not covered by if or elif. Optional — but often useful for default behavior or error messages.
alter = 15
if alter >= 16:
print("Du darfst Moped fahren")
else:
print(f"Noch {16 - alter} Jahre warten")enumerate()
Returns both index AND value in a loop: for i, name in enumerate(list):. Practical when you need the position of each element.
fruechte = ["Apfel", "Banane", "Kirsche"]
for index, frucht in enumerate(fruechte, start=1):
print(f"{index}. {frucht}")
# 1. Apfel
# 2. Banane
# 3. KirscheException
An error that interrupts the normal program flow. With try/except you catch it and react — instead of the program crashing.
try:
zahl = int(input("Zahl: "))
ergebnis = 100 / zahl
print(ergebnis)
except ValueError:
print("Das war keine Zahl!")
except ZeroDivisionError:
print("Division durch Null!")F 5 Terms
File I/O
Reading and writing files. with open("file.txt") as f: opens a file safely. Important for data storage and processing.
# Writing
with open("notiz.txt", "w") as f:
f.write("Hello World!\n")
# Reading
with open("notiz.txt", "r") as f:
inhalt = f.read()
print(inhalt)float
A data type for decimal numbers: 3.14, -0.5, 2.0. Stored internally as a floating-point number — watch out for rounding errors in very precise calculations!
pi = 3.14159
preis = 19.99
print(f"Pi = {pi:.2f}") # Pi = 3.14
print(f"Preis: {preis} Euro")
print(type(pi))for-Schleife
Repeats code for each element in a collection. The most common loop type in Python — elegant and easy to read.
namen = ["Anna", "Ben", "Clara"]
for name in namen:
print(f"Hello {name}!")
# Mit range
for i in range(1, 4):
print(f"Runde {i}")f-string
Formatted string with built-in variables: f"Hello {name}". The modern, recommended way to format strings in Python.
name = "Max"
alter = 16
note = 1.5
print(f"Hello {name}!")
print(f"In 5 Jahren: {alter + 5}")
print(f"Note: {note:.1f}")
print("=" * 20)Funktion (def)
A named block of code that can be reused. Defined with def, optionally with parameters and return value via return.
def quadrat(zahl):
return zahl ** 2
def begruessen(name, sprache="de"):
if sprache == "de":
return f"Hello {name}!"
return f"Hello {name}!"
print(quadrat(4))
print(begruessen("Lisa", "en"))G 2 Terms
Generator
A function with yield instead of return. It produces values "on demand" — memory-efficient for large data sets. Once exhausted, it's spent.
def zaehle_bis(n):
for i in range(1, n + 1):
yield i
for zahl in zaehle_bis(5):
print(zahl)
# Memory efficient!
quadrate = (x**2 for x in range(1000000))global
Makes a variable outside a function mutable. Often considered a "code smell" — better to pass values in and return them.
counter = 0
def erhoehe():
global counter
counter += 1
print(f"Counter: {counter}")
erhoehe() # Counter: 1
erhoehe() # Counter: 2H 1 Term
Hash / Hashable
A value that has a fixed "identity number" and doesn't change. Strings and numbers are hashable (valid as dictionary keys), lists are not.
mein_set = {1, 2, 3}
mein_set.add(4)
# Not hashable (mutable)
# liste = [1, 2]
# my_set.add(list) # TypeError!I 5 Terms
if / elif / else
Conditional execution: When a condition is true, the code block is executed. The foundation for decisions in programs.
temperatur = 25
if temperatur > 30:
print("Zu heiss!")
elif temperatur > 20:
print("Angenehm")
else:
print("Zu kalt")import
Loads external modules or libraries into your program: import random or from math import sqrt. Python has thousands of available modules.
import random
import math
from datetime import datetime
wuerfel = random.randint(1, 6)
wurzel = math.sqrt(16)
jetzt = datetime.now()
print(f"Wuerfel: {wuerfel}")
print(f"Wurzel: {wurzel}")Index
The position of an element in a list. Python starts at 0: list[0] is the first element. Negative indices count from the end: list[-1] is the last.
farben = ["Rot", "Gruen", "Blau"]
print(farben[0]) # Rot
print(farben[-1]) # Blau
print(farben[1:3]) # [Gruen, Blau]
print(farben.index("Gruen")) # 1int
The data type for integers: 42, -7, 0. Python can handle arbitrarily large integers — without overflow like in other languages.
alter = 16
# Konvertierung
text = "42"
zahl = int(text)
print(zahl + 8) # 50
print(type(alter))
print(10 // 3) # 3Iterable
An object that can be traversed element by element: lists, strings, dictionaries, sets. Everything that works in a for loop.
for char in "Python":
print(char)
for key in {"a": 1, "b": 2}:
print(key)
# Alles Iterables: String, Liste, Dict, Tuple, SetJ 2 Terms
join()
Joins list elements into a string: ",".join(["a", "b", "c"]) results in "a,b,c". A string method — the reverse of split().
woerter = ["Python", "ist", "toll"]
satz = " ".join(woerter)
print(satz) # Python ist toll
print("a,b,c".split(",")) # [a, b, c]JSON
A universal data format for data exchange. Python can seamlessly convert JSON to dictionaries with json.load() and json.dump().
import json
daten = {"name": "Max", "alter": 16}
with open("daten.json", "w") as f:
json.dump(daten, f, indent=2)
with open("daten.json", "r") as f:
geladen = json.load(f)K 3 Terms
Key (Dictionary)
The "name" in a key-value pair. Must be unique and immutable (hashable). Strings and numbers are the most common key types.
nutzer = {"name": "Lisa", "alter": 17}
print(list(nutzer.keys()))
print(list(nutzer.values()))
for key, value in nutzer.items():
print(f"{key}: {value}")Klasse (class)
Blueprint for objects. Packages data (attributes) and functions (methods) together. The basis of object-oriented programming in Python.
class Auto:
def __init__(self, marke, farbe):
self.marke = marke
self.farbe = farbe
def beschreibung(self):
return f"Ein {self.farbe}es {self.marke}"
mein_auto = Auto("VW", "blau")
print(mein_auto.beschreibung())*args / **kwargs
Receive any number of arguments: *args as a tuple, **kwargs as a dictionary. Flexible function signatures for advanced patterns.
def profil_anzeigen(**daten):
for key, value in daten.items():
print(f"{key}: {value}")
profil_anzeigen(name="Max", alter=16, stadt="Wien")
# Any number of named arguments!L 4 Terms
Lambda
An anonymous, one-line function: square = lambda x: x**2. Compact for small operations — often used with map(), filter(), or sorted().
quadrat = lambda x: x ** 2
print(quadrat(5)) # 25
spieler = [{"name": "Anna", "punkte": 95}]
spieler.sort(key=lambda s: s["punkte"])len()
Returns the length of an object: number of elements in a list, characters in a string, entries in a dictionary. One of the most frequently used built-in functions.
text = "Hello World"
zahlen = [1, 2, 3, 4, 5]
print(len(text)) # 10
print(len(zahlen)) # 5
if len(zahlen) > 0:
print("Liste hat Eintraege")Liste (list)
Ordered, mutable collection of values. Created with square brackets. The most important data structure in Python for almost all use cases.
aufgaben = ["Python", "CSS", "HTML"]
aufgaben.append("JavaScript")
print(aufgaben[0])
print(aufgaben[-1])
print(len(aufgaben))
for i, a in enumerate(aufgaben):
print(f"{i+1}. {a}")Loop / Schleife
Repeats code multiple times. for for collections, while for conditional repetition. The most efficient way to automate repetitive tasks.
# for loop
for i in range(5):
print(i)
# while loop
zahl = 1
while zahl <= 5:
print(zahl)
zahl += 1
# Infinite loop with break
while True:
if input("Exit? ") == "Exit":
breakM 4 Terms
Methode
A function that belongs to an object. list.append("x") or string.upper() — called with a dot after the object.
text = "Hello World"
print(text.upper())
print(text.replace("World", "Python"))
zahlen = [3, 1, 4]
zahlen.sort()
print(zahlen) # [1, 3, 4]Modul
A Python file containing functions and classes. With import you load them into your program. Python has a huge ecosystem of modules.
# hilfen.py
def durchschnitt(zahlen):
return sum(zahlen) / len(zahlen)
if __name__ == "__main__":
print(durchschnitt([1, 2, 3]))
# main.py
import hilfen
print(hilfen.durchschnitt([4, 5, 6]))Mutable / Immutable
Mutable: lists, dictionaries, sets. Immutable: strings, tuples, numbers. Mutable objects can still be changed after creation.
# Mutable
liste = [1, 2, 3]
liste.append(4)
print(liste) # [1, 2, 3, 4]
# Immutable
text = "Hello"
text = text.lower() # New object!__main__
The entry point of a Python program. if __name__ == "__main__": ensures that code only runs when started directly — not on import.
# hilfen.py
def addiere(a, b):
return a + b
if __name__ == "__main__":
print(addiere(2, 3))
# main.py
import hilfen
# Der Test-Code oben laeuft NICHT!N 2 Terms
None
Python's version of "nothing". A function without return automatically returns None. Useful to signal "no value yet".
def gruessen(name):
print(f"Hello {name}!")
# Kein return
ergebnis = gruessen("Max")
print(ergebnis) # NoneNamespace
A "namespace" where variable names are unique. Every module, function, and class has its own namespace — this prevents name collisions.
name = "Global"
def funktion():
name = "Lokal"
print(name) # Lokal
funktion()
print(name) # GlobalO 3 Terms
OOP
Object-oriented programming: Code is organized in objects that combine data and functions. Classes, inheritance, polymorphism — the basis of large programs.
class Tier:
def __init__(self, name):
self.name = name
def laut(self):
return "..."
class Hund(Tier):
def laut(self):
return "Wuff!"
bello = Hund("Bello")
print(bello.laut()) # Wuff!open()
Opens a file for reading or writing. Combined with with for safe file operations: with open("file.txt") as f: — closes automatically.
# Reading
with open("datei.txt", "r") as f:
inhalt = f.read()
# Writing
with open("datei.txt", "w") as f:
f.write("Neuer Text")
# Appending
with open("log.txt", "a") as f:
f.write("Neuer Eintrag\n")Operator
Symbols for calculations and comparisons: +, -, *, /, ==, !=, >, and, or, not. The building blocks of all expressions in Python.
a = 10
b = 3
print(a + b) # 13
print(a // b) # 3
print(a % b) # 1
print(a > b) # True
print(a == 10) # TrueP 5 Terms
Parameter
A placeholder in a function definition: def greet(name): — name is the parameter. When called, an argument is passed that fills the parameter.
def begruessen(name, sprache="de"):
if sprache == "de":
return f"Hello {name}!"
return f"Hello {name}!"
print(begruessen("Max"))
print(begruessen("Lisa", "en"))pip
Python's package manager. Installs external libraries: pip install requests. The gateway to Python's huge ecosystem of over 400,000 packages.
# Paket installieren
$ pip install requests
# Alle installierten Pakete
$ pip list
# In virtueller Umgebung
$ python -m venv venv
$ source venv/bin/activateprint()
Outputs text to the console. The first function every Python learner encounters. With sep and end you can customize the behavior.
name = "Max"
alter = 16
print("Hello", name)
print(f"Hello {name}!")
print("a", "b", "c", sep="-") # a-b-c@property
Turns a method into a readable attribute. @name.setter allows controlled setting. Elegant for encapsulated class attributes.
class Kreis:
def __init__(self, radius):
self._radius = radius
@property
def flaeche(self):
return 3.14159 * self._radius ** 2
k = Kreis(5)
print(k.flaeche) # 78.54PyBuddy
Your project in the Python Classic course — an AI assistant that you expand chapter by chapter. From a simple chatbot to an interactive helper with file I/O.
# Your PyBuddy CLI project
import pybuddy
pybuddy.begruessen("Max")R 4 Terms
range()
Generates a sequence of numbers: range(5) → 0,1,2,3,4. range(2, 10, 2) → 2,4,6,8. The for loop's best friend for counting tasks.
# 0 bis 4
for i in range(5):
print(i)
# 1 bis 5
for i in range(1, 6):
print(i)
# Nur gerade
for i in range(0, 10, 2):
print(i)Rekursion
A function that calls itself. Always needs a termination condition, otherwise infinite loop. Elegant for tree structures and mathematical problems.
def fakultaet(n):
if n <= 1:
return 1
return n * fakultaet(n - 1)
print(fakultaet(5)) # 120
# 5! = 5 * 4 * 3 * 2 * 1 = 120return
Returns a value from a function and ends it. Without return, a function returns None. The heart of data processing.
def addiere(a, b):
return a + b
def ist_gueltig(alter):
if alter >= 18:
return True
return False
print(addiere(5, 3)) # 8
print(ist_gueltig(20)) # Trueraise
Raises an exception yourself: raise ValueError("Invalid input"). Useful to detect errors early and give clear error messages.
def teilen(a, b):
if b == 0:
raise ValueError("Nicht durch Null!")
return a / b
try:
print(teilen(10, 0))
except ValueError as e:
print(f"Fehler: {e}")S 6 Terms
self
Refers to the current object in a class. The first parameter of every method (except static). self.name accesses the object's attribute.
class Schueler:
def __init__(self, name):
self.name = name
def vorstellen(self):
return f"Ich bin {self.name}"
max = Schueler("Max")
print(max.vorstellen()) # Ich bin MaxSet
An unordered collection without duplicates. {1, 2, 3} or set(list). Perfect for set operations like union and intersection.
zahlen = {1, 2, 3, 3, 3}
print(zahlen) # {1, 2, 3}
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3}Slicing
Cutting out parts: list[0:3] → elements 0 to 2. text[::-1] → text reversed. One of Python's most elegant features.
text = "Python ist toll"
zahlen = [0, 1, 2, 3, 4, 5]
print(text[0:6]) # Python
print(text[::-1]) # llot tsi nohtyP
print(zahlen[1:4]) # [1, 2, 3]
print(zahlen[::2]) # [0, 2, 4]String (str)
Text in Python: "Hello World". Immutable and extremely versatile. Methods like .upper(), .split(), .replace() make text processing easy.
name = "Python"
print(name.upper())
print(name.replace("P", "J"))
print(f"Ich lerne {name}")
print(" hallo ".strip())SyntaxError
An error that occurs when Python's grammar is violated: forgotten colon, wrong indentation, missing bracket. The most common beginner error source.
# CORRECT
def begruessen(name):
return f"Hello {name}!"
# ERROR: Forgotten colon
def begruessen(name)
return "Hello!"
# SyntaxError: expected :@staticmethod / @classmethod
Methods that don't need self. @staticmethod is a normal function in a class. @classmethod receives the class itself (cls).
class Mathe:
@staticmethod
def addiere(a, b):
return a + b
print(Mathe.addiere(5, 3)) # 8T 4 Terms
try / except
Catches errors so the program doesn't crash. try: attempts something, except: reacts to the error. Optional with else and finally.
try:
datei = open("daten.txt")
inhalt = datei.read()
except FileNotFoundError:
print("Datei nicht gefunden!")
inhalt = "Standardwert"
finally:
print("Wird immer ausgefuehrt")Tupel (tuple)
Like a list, but immutable: (1, 2, 3). After creation, no elements can be added or removed. Safer for constant data.
koordinaten = (10, 20)
farbe = (255, 128, 0)
print(koordinaten[0]) # 10
x, y = koordinaten
print(f"x={x}, y={y}")
# Tupel sind immutable!type()
Returns the data type of a value: type(42) → <class 'int'>. With isinstance() you check whether a value has a certain type.
name = "Lisa"
alter = 16
print(type(name)) # <class str>
print(type(alter)) # <class int>
if type(alter) is int:
print("Ganzzahl!")Type Hinting
Optional type annotations for better readability: def add(a: int, b: int) -> int:. Python doesn't enforce them, but IDEs and tools use them for better support.
from typing import List, Dict
def summe(zahlen: List[int]) -> int:
return sum(zahlen)
print(summe([1, 2, 3])) # 6V 3 Terms
Variable
A named storage box for data. The building block of every program. Python recognizes the data type automatically — no declaration needed.
name = "Max"
alter = 16
# Mehrfachzuweisung
x, y, z = 1, 2, 3
print(f"{name} ist {alter} Jahre alt")venv
Virtual Environment — an isolated Python workspace. Every project gets its own libraries. Prevents version conflicts between projects.
# Create virtual environment
$ python -m venv venv
# Activate
$ venv\Scripts\activate # Windows
$ source venv/bin/activate # Mac/Linux
$ pip install requestsVererbung
A class inherits attributes and methods from another: class Dog(Animal):. Avoids code repetition and enables specialization.
class Tier:
def __init__(self, name):
self.name = name
class Hund(Tier):
def laut(self):
return "Wuff!"
class Katze(Tier):
def laut(self):
return "Miau!"
for tier in [Hund("Bello"), Katze("Mimi")]:
print(f"{tier.name}: {tier.laut()}")W 3 Terms
while-Schleife
Repeats code as long as a condition is true. Needs a termination condition, otherwise infinite loop. Good for an unknown number of repetitions.
antwort = ""
while antwort != "ja":
antwort = input("Nochmal? ")
# Mit Zaehler
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Los!")with-Statement
Ensures clean resource management: with open("file.txt") as f:. Closes the file automatically — even on errors. Cleaner and safer.
# Automatic closing
with open("daten.txt", "r") as f:
inhalt = f.read()
# f is already closed here!Walrus Operator (:=)
Assignment AND return in one step: if (n := len(text)) > 10:. Saves lines but can affect readability. Available since Python 3.8.
# Without walrus
name = input("Name: ")
while name != "exit":
print(f"Hello {name}!")
name = input("Name: ")
# With walrus
while (name := input("Name: ")) != "exit":
print(f"Hello {name}!")Z 1 Term
zip()
Combines multiple lists pairwise: zip(names, ages) → ("Max", 16), ("Lisa", 17). Often used with for name, age in zip(...).
namen = ["Anna", "Ben"]
noten = [1, 2]
for name, note in zip(namen, noten):
print(f"{name}: Note {note}")
woerterbuch = dict(zip(namen, noten))
print(woerterbuch) # {Anna: 1, Ben: 2}