← All lessons

Mini project: "Guess the number"

Sign in · Sign up

Lesson 3.9

Let's build the whole game: the computer picks a number and the player guesses it in three tries.

import random

secret = random.randint(1, 10)
attempts = 3

while attempts > 0:
    guess = int(input("Guess a number from 1 to 10: "))
    ...                             # checks, hints, exits

Let's go through the new details:

  • random.randint(1, 10) gives a random number from 1 to 10, both ends included;
  • int(input(...)) turns the answer into a number: without int, comparing a number with a string won't work;
  • attempts -= 1 lowers the counter — without it the game never ends;
  • break on a win leaves the loop, and if attempts == 0 after the loop reports a loss.

In this check the secret number and the player's answers are set by the check: random.randint returns the number from the test, and the answers are put in place of input(). That way every run plays the same scenario of the game.

Hint

The game is a loop that ends with a win or with the attempts running out.

Inside: int(input(...)), a comparison with the secret and a break on a win. After the loop, check whether the attempts ran out and print the result.