What Are Loops?

Understand why the quiz needs to repeat code for each question

Right now, PyQuiz asks one question and stops. A real quiz asks several. You could copy the quiz code three times, but that approach breaks the moment you want to add a fourth question — you would have to touch the code again.

The better approach is a loop: a block of code that runs multiple times, once for each item in a collection.

The for loop

A for loop repeats a block of code for each item in a sequence:

for i in range(3):
    print(f"Round {i + 1}")

Round 1
Round 2
Round 3

range(3) produces the numbers 0, 1, 2. The variable i takes each value in turn. The indented block runs once per value.

Looping over a collection

You can also loop over a list of items directly:

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

red
green
blue

color takes the value "red", then "green", then "blue" — one per iteration.

The while loop

A while loop runs as long as a condition stays True:

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Go!")

3
2
1
Go!

Use for when you know how many iterations you need. Use while when the number depends on something that changes — like a player deciding to stop.

In the next chapter, you will replace the single hardcoded question with a list of three questions and loop through them.

Next Chapter →