Course 4.2Lesson 5 of 5
In this project we write a number guessing game with hints and a limit of tries. We write the rules first, plan the loop with the conditions that end it (the player wins, or the tries are used up), build the game from the simple version of the last lesson, test the cases that end the game in different ways, and extend it with a random secret, a best score and a play-again question. The project uses a while loop with two reasons to stop, input(), if, elif and else, and a flag variable.
Try the code and the simulations beside the lesson.
After this lesson you can
The computer has a secret number. The player has 6 tries to guess it. After each wrong guess, the program says Too low or Too high. If the player guesses the number, the player wins. If the six tries are used up, the player loses, and the program shows the secret.
A loop needs a condition. Here the game ends for two different reasons: the player wins, or the tries are all used. The loop must continue while neither has happened.
tries < max_tries and the player has not won.True or False. We call it won, and it starts as False.The condition is then while tries < max_tries and not won:. Read it aloud: "while there are tries left and the player has not won".
The last point is important. The loop does not know why it stopped. The flag tells the program.
A game can end in three ways, and each needs a test.
| Guesses typed | What should happen |
|---|---|
42 | win on the first try, 1 tries |
50, 30, 42 | win on the third try |
1, 2, 3, 4, 5, 6 | lose after six tries, the secret is shown |
Check the edge as well: the winning guess on the last try, which is the sixth. Type 1, 2, 3, 4, 5, 42. The program should say that the player wins.
This is a strategy for the player, not for the program. Try it in the game: guess the middle each time.
Pick one, and do it without looking at a solution. Test again after each change.
import random and secret = random.randint(1, 100). Now the game is different each time.Very close when the guess is within 3 of the secret.Play again? (y/n).Guess 0 of 6.input() into a number.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
and.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
won?while tries < max_tries and not won: mean in words?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.