Python — Grundlagen
Kapitel 3 · Theorie

Kontrollstrukturen

if / elif / else

punkte = 87
if punkte >= 90:
    note = "A"
elif punkte >= 80:
    note = "B"
elif punkte >= 70:
    note = "C"
else:
    note = "D"

for-Schleife — über Iterables

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

for name in ["Anna", "Bert", "Cora"]:
    print(name)

for i, name in enumerate(namen):
    print(f"{i}: {name}")

for k, v in dictionary.items():
    print(k, "→", v)

while-Schleife — solange Bedingung

zahl = 0
while zahl < 10:
    if zahl == 5:
        zahl += 2
        continue       # nächste Iteration
    if zahl > 8:
        break          # raus
    print(zahl)
    zahl += 1

List Comprehension — die Python-Magie

# Statt for-Schleife mit append
quadrate = [x*x for x in range(10)]
geraden = [x for x in range(20) if x % 2 == 0]
matrix = [[i*j for j in range(3)] for i in range(3)]
🎯
Indentation mattersPython nutzt Einrückung statt {}. Standard: 4 Leerzeichen. Tabs vermeiden — Mischung führt zu IndentationError. PEP-8 ist Pflicht-Lektüre.
Zurück zu Informatik