Project: Guessing game
A classic: the computer knows a secret number and the player keeps guessing, getting hints, until they hit it.
You need a loop that keeps going until the guess is right, a counter for tries, and if/elif for the hints.
See it run
secret = 7 guess = 5 tries = 1 while guess != secret: guess = guess + 1 tries = tries + 1 print(tries)
The core of a guessing game: loop until the guess matches, counting as you go. (guess + 1 stands in for a new input() each pass.)
Practice project: guessing game
Exercise 1
secret = 31. Keep asking for an int guess until it matches. After each wrong guess print Too high or Too low. When correct, print You got it in 4 tries! (use the real count).
The player types 50, 25, 37, 31.
Exercise 2
Give the guessing game a three-try limit with secret = 8. Read integer guesses into guess, counting each in tries. Wrong guesses print Too low or Too high. On a win print Won in N tries; if all three miss, print Out of tries. Inputs are 3, 9, 8: a win on the final allowed try still counts.
Exercise 3
A player can type quit. With secret = 12, read into text until a win, quit, or three numeric guesses. Convert each numeric entry into guess and count it in tries; print Too low for a guess below the secret and Too high for one above. Quit leaves guess as the last numeric guess, prints Cancelled after N tries and stops reading. Inputs are 5, then quit: after quit, do not call input() again. On other exits print Won in N tries or Out of tries. Replace N with tries in each message.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.