Lernziele dieses Kapitels
- You use for loops with range() for targeted repetitions
- You control while loops with termination conditions and avoid infinite loops
- You use break, continue and enumerate() for elegant iteration
- You build PyBuddy's interactive menu
The for Loop
The for loop is the most common repetition in Python. It iterates over every element of a sequence — be it a list, a string, or a range() object.
range(start, stop, step) generates number sequences. Important: The stop value is exclusive!
# for loop with range()
for i in range(1, 6):
print(f"Round {i}")
# With step size
for i in range(0, 11, 2):
print(f"Even number: {i}")
# Iterate over strings
for buchstabe in "Python":
print(buchstabe.upper())
Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:
for i in range(1, 6):
print(i)
for (let i = 1; i < 6; i++) {
console.log(i);
}
range(1, 6) gives 1-5. JavaScript: i < 6 also gives 1-5. Python's for is more intuitive, JS needs the classic C syntax.The while Loop
while repeats code as long as a condition is True. It is perfect when you don't know how many times something needs to be repeated — e.g. until the user enters 'exit'.
Warning
Never forget the termination condition, otherwise the loop runs forever — this is called an infinite loop!
# while loop: Countdown
countdown = 3
while countdown > 0:
print(f"Starting in {countdown}...")
countdown -= 1
print(" Go!")
# User input until 'exit'
befehl = ""
while befehl != "exit":
befehl = input("Command (exit to quit): ").lower()
if befehl != "exit":
print(f"Executing: {befehl}")
print(" Program ended.")
Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:
while befehl != "exit":
befehl = input("> ")
while (befehl !== "exit") {
befehl = prompt("> ");
}
input() in the terminal, JavaScript prompt() as a popup.break & continue
Sometimes you want to abort a loop early or skip an iteration. For that there are break and continue:
break— ends the loop immediatelycontinue— skips the rest of the current iteration
# break: End loop early
for i in range(1, 11):
if i == 5:
print(" Abort at 5!")
break
print(i)
# continue: Skip
for i in range(1, 6):
if i == 3:
print("⏭️ Skipping 3")
continue
print(f"Processing {i}")
Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:
if i == 5:
break
if i == 3:
continue
if (i === 5) { break; }
if (i === 3) { continue; }
break and continue work in Python and JavaScript exactly the same!enumerate() & zip()
enumerate() delivers the index and the value simultaneously during an iteration — super practical! zip() combines two lists element by element.
# enumerate: Index + Value
aufgaben = ["Learn Python", "Do exercises", "Build project"]
for index, aufgabe in enumerate(aufgaben, start=1):
print(f"{index}. {aufgabe}")
# zip: Combine lists
namen = ["Anna", "Ben", "Clara"]
punkte = [95, 87, 92]
for name, punkt in zip(namen, punkte):
print(f"{name}: {punkt} points")
List Comprehensions
List Comprehensions are Python's superpower: You create a new list in a single line. It is faster and more readable than a classic for loop.
Pro Tip
List comprehensions can also contain conditions: [x for x in liste if x > 0] filters automatically.
# Classic vs. Comprehension
zahlen = [1, 2, 3, 4, 5]
# Classic
quadrate_alt = []
for z in zahlen:
quadrate_alt.append(z ** 2)
# Comprehension (one line!)
quadrate_neu = [z ** 2 for z in zahlen]
print(quadrate_neu) # [1, 4, 9, 16, 25]
# With condition: only even numbers
gerade = [z for z in zahlen if z % 2 == 0]
print(gerade) # [2, 4]
# Transform strings
woerter = ["python", "is", "cool"]
gross = [w.upper() for w in woerter]
print(gross) # ['PYTHON', 'IS', 'COOL']
Warm-Up: Multiplication Table
Write a program that reads a number and outputs the multiplication table from 1-10.
Hinweis: z = int(input("Number: "))
for i in range(1, 11):
print(f"{i} x {z} = {i * z}")
z = int(input("Number: "))
for i in range(1, 11):
print(f"{i} x {z} = {i * z}")
Challenge: Number Guessing
Program a number guessing game! The computer picks a number 1-100. The player guesses until they get it right. After each guess comes 'too high' or 'too low'.
Hinweis: import random
ziel = random.randint(1, 100)
versuche = 0
while True:
tipp = int(input("Your guess: "))
versuche += 1
if tipp < ziel:
print("Too low!")
elif tipp > ziel:
print("Too high!")
else:
print(f" Correct! {versuche} attempts.")
break
import random
ziel = random.randint(1, 100)
versuche = 0
while True:
tipp = int(input("Your guess: "))
versuche += 1
if tipp < ziel:
print("Too low!")
elif tipp > ziel:
print("Too high!")
else:
print(f" Correct! {versuche} attempts.")
break
PyBuddy Checkpoint: Menu Loop
PyBuddy shows an interactive menu and repeats until the user enters 'exit'. Use while and if-elif.
Hinweis: # pybuddy/main.py
print(" PyBuddy is ready!")
while True:
cmd = input("
[Command: hello, time, exit] ").lower()
if cmd == "exit":
print(" See you soon!")
break
elif cmd == "hello":
print(" Hello! How are you?")
elif cmd == "time":
import datetime
print(f"🕒 {datetime.datetime.now().strftime('%H:%M')}")
else:
print("❓ Unknown command.")
# pybuddy/main.py
print(" PyBuddy is ready!")
while True:
cmd = input("
[Command: hello, time, exit] ").lower()
if cmd == "exit":
print(" See you soon!")
break
elif cmd == "hello":
print(" Hello! How are you?")
elif cmd == "time":
import datetime
print(f"🕒 {datetime.datetime.now().strftime('%H:%M')}")
else:
print("❓ Unknown command.")
In Tetris an infinite loop constantly checks: Is there a complete row? If yes → delete it, update score, speed up the game. That's exactly what you do with while and if — just with more graphics!
Zusammenfassung
- for → iterate element by element
- while → as long as condition is True
- break / continue for flow control
- enumerate() and zip() for elegant iteration
- List Comprehensions: [x*2 for x in liste]