Python for Humans · Draft v0.4 · Oct 27, 2026 · Draft position: chapter 3 · Add runnable starters for replay and guessing; keep one game to modify and make the five-guess extension optional.
Loops
- You should already know
- Variables, input and f-strings (chapter 1); if, elif, else and indentation (chapter 2).
- You'll build
- Replay your adventure and build a guess-the-number game.
- You'll be able to
- Repeat instructions with while, leave a loop with break, and convert input to a number. Optionally, repeat a fixed number of times with for and range.
Our castle adventure has a short life. Choose a door, meet a dragon or find some treasure, and the program ends.
You can click Run again, but what if the program could ask whether you'd like another go?
We need a way to tell Python to repeat some instructions. That's called a loop.
In the first two chapters, most examples were ready to run. This time, you'll start writing more of the code yourself. We'll work through the first loops together, then you'll build on them. Keep the earlier examples nearby when you need a reminder.
Once More?
Before we bring back the castle, let's try a very small program.
Click Run. Answer yes a couple of times, then answer no.
again = "yes" while again == "yes": print("The dragon would like another pizza.") again = input("Feed the dragon again? (yes/no) ") print("The dragon settles down for a nap.")
The word while introduces our loop. It means: while this condition is true, run the indented instructions.
We start by giving again the value "yes". Python reaches while again == "yes": and checks the condition. It matches, so Python prints the message and asks a question.
Here's the new part: when Python reaches the end of the indented block, it goes back to the while line and checks again.
If you answered yes, it runs the block another time. If you answered no, the condition is no longer true. Python skips the block and continues with the final print().
That last line isn't indented, so it isn't part of the loop.
What happens if you answer maybe? Try it. Just like our earlier pizza program, we're checking for one exact string. Anything other than yes ends this loop.
One more experiment: Change the first line to again = "no". Predict what the program will display, then run it.
The condition is checked before the block runs. A loop can run many times, once, or not at all.
When a Loop Won't Stop
What would happen if we removed the line that asks whether to feed the dragon again?
again would stay "yes". Python would keep printing the pizza message, going back to the condition, and finding it true. Forever, unless we stopped it.
That's an infinite loop. It's an easy mistake to make.
If an example on this page keeps running, click Reset in its code box. That stops the program and restores the original code. It also works when a program is waiting for an answer. You may see KeyboardInterrupt, which means the running program was interrupted.
We won't deliberately flood the page with pizza messages. But keep Reset in mind as you experiment: every loop needs some way to finish, or some way for you to stop it.
Back to the Castle
Now let's put our adventure inside a loop.
We're using a trimmed-down version of the castle from the last chapter so we can see what's changed.
print("Welcome to the Mysterious Castle!") again = "yes" while again == "yes": print("Ahead are two doors: one red and one blue.") door = input("Which door do you choose? (red/blue) ") if door == "red": print("You discover a sleeping dragon!") elif door == "blue": print("You find a chest full of treasure!") else: print("You decide to stay in the hallway.") again = input("Play again? (yes/no) ") print("Thanks for visiting. Mind the dragon on your way out.")
Choose the red door, answer yes, then choose the blue door. You can explore both paths without restarting the program.
Look at the indentation. Everything inside the while block has moved four spaces to the right. The lines inside if, elif and else have moved another four spaces.
But the question Play again? lines up with if, not with the dragon's message. It belongs to the loop, so we ask it after every path.
The welcome message sits above the loop. It runs just once. The farewell sits below the loop and runs when we're finished playing.
Try it yourself: Move the welcome message inside the loop. What changes? Where would you put a message you wanted the player to see only after leaving the castle?
Add Replay to Your Adventure
Now try the same idea with the adventure you made in chapter 2. Here's a starting point with the loop already in place. Run it once before making changes.
print("Welcome back to my adventure!") again = "yes" while again == "yes": print("Your adventure goes here.") again = "no" print("Thanks for playing!")
For now, again = "no" makes the starter stop after one trip around the loop. You'll replace that line with a replay question.
Work through these changes one at a time:
- Replace
print("Your adventure goes here.")with the questions and decisions from your adventure. You can copy your own code here. Move those lines four spaces to the right, keeping the extra indentation inside each decision. - Run it and check one path. It should still finish after one play.
- Replace
again = "no"with a line that asksPlay again? (yes/no)and stores the answer inagain. Keep it inside the loop, after all the paths. Look at the castle example if you need a reminder.
Check that you can play two different paths in one run, then leave. Does the replay question appear after every ending? If something goes wrong, compare the indentation with the castle example above.
Leaving Through a Different Door
Sometimes we want to leave a loop in the middle of its instructions.
Maybe the player wants to quit before choosing a door. We can give them that option with break.
print("Welcome to the Mysterious Castle!") while True: door = input("Choose a door: red, blue, or quit: ") if door == "quit": break if door == "red": print("You discover a sleeping dragon!") elif door == "blue": print("You find a chest full of treasure!") else: print("There isn't a door that color. Try another one.") print("You leave the castle.")
Choose a few doors, then type quit.
We've changed the loop's condition to True. Where did that come from?
Every condition we've written has an answer. Python can show it to us:
print("red" == "red") print("red" == "blue")
When we ask whether two values are equal, Python answers with True or False. Both start with a capital letter. if and while look at that answer to decide what to do.
Instead of asking a question, we can write the answer directly. Since True stays true, while True: keeps repeating unless something stops it.
That's the job of break. When the player types quit, Python reaches break and immediately leaves the loop. It doesn't check the door colors or ask another question. Execution continues at print("You leave the castle.").
Although break is inside an if, it exits the loop. The if decides whether we reach it.
Notice that we no longer need again. In the earlier program, the condition at the top decided when to stop. Here, a decision inside the loop leads to break. Both are useful ways to control repetition.
Predict first: If you type quit as your very first answer, which messages will you see? Run it and check.
Guess My Number
Our adventure can now keep running. Let's use that ability for a different game.
The computer has a secret number. You make a guess, and it tells you whether to go higher or lower. You keep guessing until you find it.
We'll start with a secret we choose ourselves. But first, we need to deal with a small surprise from input().
guess = input("Enter a number: ") print(guess + guess)
Enter 7. Were you expecting 14?
Remember "2" + "2" from the introduction? input() always gives us a string. Even when you type digits, the result is text. Adding "7" to "7" gives us "77".
For our game, we need a number we can compare with the secret. Python's int() converts a string such as "7" into the whole number 7.
answer = input("Enter a whole number: ") guess = int(answer) print(guess + guess)
Try 7 again. Now we get 14.
You might see those first two lines combined:
guess = int(input("Enter a whole number: "))
Python asks the question with input(), passes the answer to int(), then gives the resulting number the name guess. We'll use that shorter form in the game.
Break it on purpose: Enter seven instead of 7 in the box above.
You'll get a ValueError: int() can't turn that text into a whole number. 7.5 won't work here either. For now, enter whole numbers written as digits. In Errors and Debugging, we'll learn how to handle an error and ask the player to try again.
Higher or Lower?
Before you build the game, here are the comparisons it needs. The symbol < means less than, and > means greater than. Like ==, each comparison gives us True or False.
secret = 7 guess = 3 print(guess < secret) print(guess > secret) print(guess == secret)
Predict the three answers, then run it. Change guess to 9, then to 7, and check again.
Now write a game that does these things:
- Keeps the secret number
7for the whole game. - Repeatedly asks for a whole-number guess.
- Prints
Higher!if the guess is too small, orLower!if it's too big. - Prints
You got it!and leaves the loop when the guess is right. - Thanks the player after the loop ends.
The secret, loop and number conversion are already in place below. Run this starter once. It asks for one guess, then stops because of break.
secret = 7 print("I'm thinking of a number from 1 to 10.") while True: guess = int(input("What's your guess? ")) break print("Thanks for playing.")
Your job is to replace that break with the decisions. Start with an if that checks whether the guess is too small and prints a hint. Add an elif for a guess that's too big, then an else for a correct guess. Put break inside the winning branch so a wrong guess brings you back to the question.
Use the comparisons from the small example above. You're combining decisions you already know with a loop, rather than writing every part of the game at once.
Check your game with 3, 9, then 7. You should get one hint in each direction, then win. Seeing the secret in the code is useful while you're checking it.
A Worked Version
Try your own version before reading this one. If yours behaves differently, compare where each version asks for a guess and leaves the loop. Your wording doesn't need to match.
secret = 7 print("I'm thinking of a number from 1 to 10.") while True: guess = int(input("What's your guess? ")) if guess < secret: print("Higher!") elif guess > secret: print("Lower!") else: print("You got it!") break print("Thanks for playing.")
Try 3, then 9, then 7.
If the guess is too small, we print Higher!. If it's too big, we print Lower!. Otherwise, the two numbers must be equal: you've found the secret, and break ends the loop.
Notice where we ask for a guess: inside the loop. Each time we go around, we need a new answer. guess gets a new value, just as food did in our robot's memory experiment.
The secret stays outside the loop. We want the same number throughout the game.
Try it yourself: Change secret to another number from 1 to 10. Check the game with a guess below it, a guess above it, and the right answer. Do all three responses make sense?
Let Python Pick
Our game works, but knowing the answer makes it a little too easy.
Python comes with a collection of tools for working with random choices. It's called random. To use those tools, we first write:
import random
random is a module, a collection of code we can use in our own programs. It comes with Python, so there's nothing to install.
One of its tools is random.randint(). Give it two whole numbers and it chooses a random whole number between them, including both ends.
import random secret = random.randint(1, 10) print(secret)
Run it a few times. It might choose 1, 10, or any whole number in between. It can also choose the same number twice in a row. Random doesn't mean every result must be different.
The dot in random.randint means we're using the tool named randint from the random module. We'll explore modules properly in Modules and Several Files.
Keep working in your guessing game box above. You can make all the remaining game changes there; there's no need to type the program again. Type import random at the top, then replace the fixed secret with secret = random.randint(1, 10). Keep that choice before the loop so every guess is compared with the same number.
Run your updated game and see whether you can find the secret. If you need to check its hints, temporarily add print(secret) before the loop, then remove it when you're done.
This time, you really have to guess.
One warning: a typo such as seven, or pressing Enter without typing anything, still stops the game with a ValueError. You haven't broken anything. Click Run to start a new game. We'll make the game more forgiving later.
We choose the secret before the loop. Each guess is compared with the same number. If we moved secret = random.randint(1, 10) inside the loop, the target could change every time you guessed!
Turn up the difficulty: Make the game choose a number from 1 to 100. Remember to change its opening message, too.
Optional: Only Five Guesses
You already have a complete guessing game. If you'd like another challenge, try giving it a limit. You can also go straight to Your Turn below; we'll practice for loops in the next chapter.
So far, we've repeated instructions until something happens: the player says they're finished or guesses the right number.
Our game lets you guess forever. What if you only had five tries?
When we know how many times we want to repeat, Python has another kind of loop. Here's a small taste:
for attempt in range(1, 6): print(f"Guess number {attempt}")
This is a for loop. range(1, 6) supplies the numbers 1, 2, 3, 4, and 5, and the loop runs once for each one. Each time, attempt refers to the next number.
The first number says where to start; the second says where to stop, without including it. That's why we need 6 to reach 5.
Predict first: Change the first line to for attempt in range(5):. What numbers will you see? Run it and check.
Given just one number, range() starts at 0. You still get five numbers, 0 through 4, which is handy for counting repetitions but odd for numbering guesses. We'll stick with range(1, 6).
Make the following changes in the same guessing-game box you used above. Before editing, you can copy your working game into a note if you'd like to keep the unlimited version.
- Replace
while True:with aforloop using the range you just tried. - Use the loop variable in the question so the player sees which guess they're on.
- Keep
breakfor a correct guess. It works withfortoo. - After the loop, reveal the secret. That line runs whether the player wins or uses all five guesses.
First check with secret = 7. Enter 7 on the first guess: does the game stop immediately? Then run it again and enter 1 five times: does it stop after the fifth guess and reveal 7?
The loop can end in two ways. break leaves it early when you win. Otherwise, it runs out of numbers after five guesses and stops by itself. If you need a reminder, compare the short for example with the worked guessing game above.
When both checks work, put the random secret back and play a game. Then give the player only three guesses. What else needs to change besides the range()?
We'll use for again when we want to do something with every word in a story. For now, it gives us a short way to repeat a known number of times.
Your Turn
Predict
Before you run this, write down what you think it will print. Include the final line.
number = 1 while number < 4: print(number) number = number + 1 print(f"Finished at {number}")
number = number + 1 uses the current value, adds one, and assigns the result back to number. Trace those changes one at a time. Why is the final value different from the last number printed inside the loop?
Find the Bug
This program asks for a new guess, but keeps giving the same hint. Before you run it, look for the line that should change guess.
Run it, enter 3, then enter 7 when it asks again. Click Reset to stop it when you've seen the problem.
secret = 7 guess = int(input("What's your guess? ")) while guess < secret: print("Higher!") answer = input("Try another whole number: ") print("Your guess is at least as big as the secret.")
Where does the new answer go? Does guess ever get a new value?
Fix the program so it converts each new answer to a number and updates guess. Try 3, 5, then 7. It should ask again after the first two guesses and finish after the third.
Make the Game Yours
Choose one addition to your random guessing game. Keep using the same game box. The unlimited while version is enough; if you tried the optional five-guess version, you can use that too.
- Count the guesses. In the
whileversion, startattemptsat0before the loop. Add one after each guess withattempts = attempts + 1. When the player wins, display how many guesses they used. - Give it a personality. Replace the hints with a dragon's advice, a suspicious robot's remarks, or clues from a castle ghost.
- Add a replay choice (harder). Put the game inside another loop, as we did with the castle. Choose a new secret for each game. Remember:
breakleaves the innermost loop containing it, so winning should end the guessing loop, then let you ask whether to play again.
Start with one change and check it before adding another. You can use secret = 7 while checking the hints, then put the random choice back when you're happy with them.
A Question Worth Asking
Find one part of a loop you still have to think through. Write a question about it, including the line you're looking at and what you expected to happen.
For example: “Why does the question need to be inside this loop, but the secret number goes above it?”
What I've Learned
Write one sentence in your own words about how Python decides whether to go around a loop again. Keep it in a note you can add to as you work through the course.
What's Next?
Our programs can now talk, remember, choose, and repeat. We've used those abilities to replay an adventure and build a game that responds to our guesses.
Our adventure can ask for one choice at a time. But how could it keep a collection of supplies, like a torch, a map, and some food?
In Keeping Things Together, we'll introduce the Python panel beside the page. You'll type short commands to create a collection, inspect it, and add to it. Then we'll use a loop to work with every item.