2.2 Loops

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

2.2 Loops

Loops repeat a block of code. That way we can keep asking for a guess until the user gets it right, or run a game until it’s over.

while loop

A while loop runs while a condition is True:

count = 0
while count < 3:
    print("Hello")
    count = count + 1
# Prints Hello three times

If the condition never becomes False, the loop runs forever (infinite loop). So we usually change a variable inside the loop so that the condition eventually becomes False.

for loop

A for loop runs once for each item in a sequence (e.g. a list or a range):

for i in range(3):
    print("Number", i)
# Number 0, Number 1, Number 2

range(5) gives 0, 1, 2, 3, 4. You can use the variable (i here) inside the loop.

break

Use break to exit the loop immediately:

while True:
    answer = input("Type 'quit' to stop: ")
    if answer == "quit":
        break
    print("You said", answer)

Project: Higher–Lower guessing game

The computer picks a random number. The user guesses; the program says “Too high!”, “Too low!” or “Correct!” and keeps asking until they get it.

You’ll need:

  1. Random numbers — at the top: import random. Then: secret = random.randint(1, 100) to get a number from 1 to 100.
  2. A loopwhile True: and only break when the guess equals secret.
  3. Conditionals — compare guess to secret and print the right message.

Starter code:

import random

secret = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")

while True:
    guess = int(input("Your guess: "))
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print("Correct! Well done.")
        break

Ideas to extend: Count how many guesses they needed. Give a limited number of tries (e.g. 10). Ask if they want to play again (another loop).


Next: 3.1 Lists and arrays — storing multiple values in one variable.