DE EN

Loops

for and while — mastering repetitions with list comprehensions and Python idioms.

60 Min Mittel

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!

Python
# 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())
Ausgabe
Round 1 Round 2 Round 3 Round 4 Round 5 Even number: 0 Even number: 2 ... P Y T H O N
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
for i in range(1, 6):
    print(i)
JavaScript
for (let i = 1; i < 6; i++) {
    console.log(i);
}
Merke: Python: 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!

Python
# 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.")
Ausgabe
Starting in 3... Starting in 2... Starting in 1... Go! Command (exit to quit): hello Executing: hello Command (exit to quit): exit Program ended.
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
while befehl != "exit":
    befehl = input("> ")
JavaScript
while (befehl !== "exit") {
    befehl = prompt("> ");
}
Merke: The logic is identical! Python uses 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 immediately
  • continue — skips the rest of the current iteration
Python
# 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}")
Ausgabe
1 2 3 4 Abort at 5! 1 2 ⏭️ Skipping 3 4 5
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
if i == 5:
    break
if i == 3:
    continue
JavaScript
if (i === 5) { break; }
if (i === 3) { continue; }
Merke: 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.

Python
# 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")
Ausgabe
1. Learn Python 2. Do exercises 3. Build project Anna: 95 points Ben: 87 points Clara: 92 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.

Python
# 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']
Ausgabe
[1, 4, 9, 16, 25] [2, 4] ['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}")

Solution
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

Solution
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.")

Solution
# 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.")
Learning Break

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]