In this project you build a small game that runs in the terminal. By the end you have a complete, tested program of about sixty lines, and you will have used functions, loops, conditions, input validation, the random module and unittest together.
What the game does
The computer picks a secret whole number from 1 to 100. The player has seven guesses. After each wrong guess the game says "Too low" or "Too high". When the player wins or runs out of guesses, the game offers another round and remembers the best score.
We build it in small steps and test each one. Two things about the examples below. First, input is simulated: the examples call a small helper that feeds in typed answers, so we can show real output. The helper is only for this lesson and is not part of the game. Second, random.seed(7) is used so the secret number is the same each time. Without the seed the secret differs every run, so your own output will vary.
Step 1: the secret number and the check
Start with the two parts that need no typing. random.randint(low, high) returns a whole number between the two limits, including both. A second function compares a guess with the secret:
import random
LOW = 1
HIGH = 100
MAX_GUESSES = 7
def pick_secret(low, high):
return random.randint(low, high)
def check_guess(guess, secret):
if guess < secret:
return "low"
if guess > secret:
return "high"
return "correct"
random.seed(7)
secret = pick_secret(LOW, HIGH)
print(secret)
print(check_guess(10, secret), check_guess(90, secret), check_guess(secret, secret))42
low high correctcheck_guess returns a word and prints nothing. Keeping calculation separate from printing makes it easy to test, as you will see at the end. The capital-letter names are constants: a convention for values that do not change, so the numbers live in one place.
Step 2: reading a guess safely
Players mistype. If we wrote int(input(...)) directly, typing abc would crash the program. Instead we loop until the answer is usable. The helper below pretends the player types abc, then 150, then 33:
import builtins
def type_answers(*answers):
queue = iter(answers)
def fake_input(prompt=""):
answer = next(queue)
print(prompt + answer)
return answer
builtins.input = fake_input
def read_guess(low, high):
while True:
text = input(f"Guess a number from {low} to {high}: ")
try:
guess = int(text)
except ValueError:
print("Please type a whole number.")
continue
if guess < low or guess > high:
print(f"Stay between {low} and {high}.")
continue
return guess
type_answers("abc", "150", "33")
print("Got:", read_guess(LOW, HIGH))Guess a number from 1 to 100: abc
Please type a whole number.
Guess a number from 1 to 100: 150
Stay between 1 and 100.
Guess a number from 1 to 100: 33
Got: 33The loop only ends at return. Bad input prints a message and continue goes back to the top to ask again. Each line that starts with Guess a number shows the prompt followed by the simulated answer, as it would look on screen.
Step 3: one round of the game
A round picks a secret, then loops over the allowed number of guesses. It returns how many guesses the player needed, or None for a loss:
def play_round(low, high, max_guesses):
secret = pick_secret(low, high)
for attempt in range(1, max_guesses + 1):
guess = read_guess(low, high)
outcome = check_guess(guess, secret)
if outcome == "correct":
print(f"Correct! You needed {attempt} guesses.")
return attempt
print("Too low." if outcome == "low" else "Too high.")
print(f"{max_guesses - attempt} guesses left.")
print(f"Out of guesses. The number was {secret}.")
return None
random.seed(7)
type_answers("50", "25", "40", "42")
print("Result:", play_round(LOW, HIGH, MAX_GUESSES))Guess a number from 1 to 100: 50
Too high.
6 guesses left.
Guess a number from 1 to 100: 25
Too low.
5 guesses left.
Guess a number from 1 to 100: 40
Too low.
4 guesses left.
Guess a number from 1 to 100: 42
Correct! You needed 4 guesses.
Result: 4The seed makes the secret 42 again, and the four typed guesses home in on it. A second example shows what losing looks like, with a tiny limit of two guesses:
random.seed(7)
type_answers("1", "2")
print("Result:", play_round(LOW, HIGH, 2))Guess a number from 1 to 100: 1
Too low.
1 guesses left.
Guess a number from 1 to 100: 2
Too low.
0 guesses left.
Out of guesses. The number was 42.
Result: NoneStep 4: the main loop and best score
The final function keeps playing rounds until the player says no. It remembers the lowest number of guesses in best. The optional seed parameter exists only so we can repeat a run for this lesson. A normal run leaves it empty:
def main(seed=None):
if seed is not None:
random.seed(seed)
print(f"I am thinking of a number from {LOW} to {HIGH}.")
best = None
while True:
attempts = play_round(LOW, HIGH, MAX_GUESSES)
if attempts is not None and (best is None or attempts < best):
best = attempts
if best is not None:
print(f"Best so far: {best} guesses.")
again = input("Play again? (y/n): ").strip().lower()
if again != "y":
break
print("Thanks for playing!")
type_answers("50", "abc", "150", "25", "40", "42", "y", "20", "n")
main(seed=7)I am thinking of a number from 1 to 100.
Guess a number from 1 to 100: 50
Too high.
6 guesses left.
Guess a number from 1 to 100: abc
Please type a whole number.
Guess a number from 1 to 100: 150
Stay between 1 and 100.
Guess a number from 1 to 100: 25
Too low.
5 guesses left.
Guess a number from 1 to 100: 40
Too low.
4 guesses left.
Guess a number from 1 to 100: 42
Correct! You needed 4 guesses.
Best so far: 4 guesses.
Play again? (y/n): y
Guess a number from 1 to 100: 20
Correct! You needed 1 guesses.
Best so far: 1 guesses.
Play again? (y/n): n
Thanks for playing!Read it against the code: the second round's secret was 20, which is the next number the seeded generator produces, and the player got it in one guess, so the best score became 1.
The complete program
Put everything in one file, for example guess.py. This is the whole game. It has no seed and no simulated input, so it asks you for real guesses and the secret is different each time:
import random
LOW = 1
HIGH = 100
MAX_GUESSES = 7
def pick_secret(low, high):
return random.randint(low, high)
def check_guess(guess, secret):
if guess < secret:
return "low"
if guess > secret:
return "high"
return "correct"
def read_guess(low, high):
while True:
text = input(f"Guess a number from {low} to {high}: ")
try:
guess = int(text)
except ValueError:
print("Please type a whole number.")
continue
if guess < low or guess > high:
print(f"Stay between {low} and {high}.")
continue
return guess
def play_round(low, high, max_guesses):
secret = pick_secret(low, high)
for attempt in range(1, max_guesses + 1):
guess = read_guess(low, high)
outcome = check_guess(guess, secret)
if outcome == "correct":
print(f"Correct! You needed {attempt} guesses.")
return attempt
print("Too low." if outcome == "low" else "Too high.")
print(f"{max_guesses - attempt} guesses left.")
print(f"Out of guesses. The number was {secret}.")
return None
def main(seed=None):
if seed is not None:
random.seed(seed)
print(f"I am thinking of a number from {LOW} to {HIGH}.")
best = None
while True:
attempts = play_round(LOW, HIGH, MAX_GUESSES)
if attempts is not None and (best is None or attempts < best):
best = attempts
if best is not None:
print(f"Best so far: {best} guesses.")
again = input("Play again? (y/n): ").strip().lower()
if again != "y":
break
print("Thanks for playing!")
if __name__ == "__main__":
main()Run it with:
python3 guess.pyThe if __name__ == "__main__": line means the game starts only when you run the file directly, not when another file imports it. That is what lets tests import the functions safely.
Testing the logic
check_guess needs no typing and no randomness, so tests are simple. Save them as test_guess.py next to guess.py, or run them in the same session as here:
import unittest
class GuessTests(unittest.TestCase):
def test_low(self):
self.assertEqual(check_guess(10, 50), "low")
def test_high(self):
self.assertEqual(check_guess(90, 50), "high")
def test_correct(self):
self.assertEqual(check_guess(50, 50), "correct")
unittest.main(argv=["ignored"], exit=False)...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OKThe time on the last lines will differ on your machine. In a separate test file you would use from guess import check_guess and finish with unittest.main().
Common mistakes
- Converting input with
int()and notry. One stray letter crashes the game. - Off-by-one in the loop.
range(max_guesses)counts from 0. Userange(1, max_guesses + 1)so the first guess is number 1. - Picking the secret inside the guessing loop. The number would change on every guess. Pick it once, before the loop.
- Forgetting that
randintincludes both ends.random.randint(1, 100)can return 100, whilerandom.randrange(1, 100)cannot. - Leaving the seed in. A fixed seed makes the secret the same each run. Seed only for testing.
Exercise
Add a hint: write a function describe_distance(guess, secret) that returns "very close" when the guess is within 5 of the secret and "far" otherwise. Call it with a few values and print the results, using the secret from a seeded pick_secret.
Show one possible answer
def describe_distance(guess, secret):
if abs(guess - secret) <= 5:
return "very close"
return "far"
random.seed(7)
secret = pick_secret(LOW, HIGH)
for guess in (10, 40, 45):
print(guess, describe_distance(guess, secret))10 far
40 very close
45 very closeTo use it, call print(describe_distance(guess, secret)) inside play_round after a wrong guess.
Ideas to extend it
Let the player choose an easy or hard range, count only the wins, or add a "give up" command. If you try one, write the logic as a function first and test it before connecting it to input().
A video version of this topic is in the video course at /learn/python/.
Key points
- The game picks a secret number with random.randint and gives the player a limited number of guesses.
- Splitting the program into small functions (pick, check, read, play) makes each part easy to write and to test.
- read_guess uses a while loop with try and except so that typing text or a number out of range does not crash the game.
- random.seed makes the random numbers repeatable, which is how the sample output in this lesson was produced. Without a seed, every run is different.
- Because check_guess is a plain function, it can be tested with unittest.