Skip to content

Week 5 of 8

Loops

Instead of copying a line over and over, students make the program repeat. Using a while loop, they build a Guess the Number game that keeps asking until the player wins, giving too-high and too-low hints along the way. The secret is fixed for now; Week 7 makes it random.

Estimated time
60 minutes
Project
Guess the Number Game

The idea

A loop repeats code so you do not have to write it a hundred times. A while loop keeps going as long as its condition is true - perfect for a game that should keep asking until the player wins. Something inside the loop has to eventually make the condition false, or it runs forever. Since input() gives text, we use int() to turn the guess into a number we can compare.

What you will learn

  • Use a while loop to repeat lines until something changes.
  • Give the player as many tries as they need with a loop.
  • Combine a loop with an if to react to each guess.
  • Find and fix a loop that never stops.

New words

loop
Code that repeats instead of running once.
while
Repeats the lines below it as long as its condition stays true.
int()
Turns typed text like "7" into the number 7 so you can compare it.
infinite loop
A loop that never stops because its condition never becomes false.

Project: Guess the Number Game

Edit the starter code below and press Run to see it work. Use Reset starter code to go back to the original at any time.

main.py
Terminal

Run your program to see the output.

Expected output

Guess a number from 1 to 10: 4
Too low.
Guess a number from 1 to 10: 9
Too high.
Guess a number from 1 to 10: 7
You got it!

Mini challenge

Add a tries counter: start tries = 0, add 1 to it inside the loop, and after the loop print how many guesses it took.

Debugging challenge

This game never ends, even when the player types 7. The secret is the number 7, but input() gives back the text "7". Why are they not equal, and what turns text into a number?

Broken code

secret = 7
guess = 0
while guess != secret:
    guess = input("Guess a number from 1 to 10: ")
Show solution
Turn the typed text into a number with int():
guess = int(input("Guess a number from 1 to 10: "))

Extension challenge

Change the range to 1 to 100 and give the player only 7 tries. Stop the loop and print Out of guesses! if they run out.

Reflect

A loop let you ask again and again without repeating yourself. What part of your final game might need to repeat - the turns, the questions, the rounds?

Teacher notes

The teachable moment is the infinite loop: something inside the loop must change the variable the condition checks, or it never ends. Introduce int() only as far as needed to compare numbers. Keep the secret fixed this week so students can predict and check the behavior - randomness arrives in Week 7.

Facilitating this lesson? See the teacher & librarian guide for how to run it, common mistakes, and an offline backup activity.

Finished this lesson? Mark it complete to unlock the next week.