What you'll build
The computer picks a secret number; the player keeps guessing until they get it. Your first real game — it pulls together a while loop, input, int(), comparisons, and a counter into one program.
Requirements
The must-do parts. If any are missing, we'll ask you to take another pass.
- Use the two lines we give you to pick a secret number —
import randomandsecret = random.randint(1, 100). That one new line is the only part you don't have to figure out. - Use a
whileloop to keep asking for a guess until the player gets it right. - Convert each guess with
int()before comparing —inputalways hands you text. - After each wrong guess, print
Too high.orToo low.usingif/elif/else. - Count the guesses with a counter that starts at 0 and goes up by one each round. When they win, print how many guesses it took.
- Give the player only 7 guesses. If they run out, reveal the number and end the game. (Hint: combine the win condition with a guess limit in the
while.) - After a win, ask
Play again? (y/n)and wrap the whole thing in an outer loop so they can keep playing. - Reject guesses outside 1–100 with a nudge, without counting them against the player.
Examples
What your program should look like when it runs. Lines starting with $ are typed by you; the rest is your program.
Guess (1-100): 50
Too high.
Guess (1-100): 25
Too low.
Guess (1-100): 37
Too high.
Guess (1-100): 31
Correct! You got it in 4 guesses.Where to start
Copy this scaffold into a new file. You don't have to use it — it's just a friendly nudge.
# Number guessing game
import random
secret = random.randint(1, 100) # the computer picks 1-100; you can't see it
guesses = 0
# TODO: use a while loop to keep asking until the guess is correct
# - read a guess and convert it with int()
# - add 1 to guesses
# - print "Too high." / "Too low." / "Correct!" with if / elif / else
# - when correct, print how many guesses it tookHow we'll grade it
Four checks, four points. Three or above is passing — we'll ask you to revise anything we can't tick.
| Check | What we look for | Pt |
|---|---|---|
| It runs and ends | Starts cleanly, takes guesses, and actually stops when the player guesses right — no infinite loop. | 1 |
| Hints are correct | Too high and too low point the right direction every time. A guess equal to the secret wins. | 1 |
| Counts guesses | The final message reports the real number of guesses taken, counted by the loop — not hardcoded. | 1 |
| Reads like a game | Prompts and messages are clear enough that someone who didn't write it could play it. | 1 |