A Python project – the Guess the number game

Lesson 2 of 15 · Python projects
A more detailed version:
The same game is covered in more detail in the basic course and in the refactoring project. See: Mini project – Guess the number.

In this project we will make a simple game in Python in which the computer chooses a random number, and the player tries to guess it.

This project is excellent for practising basic Python concepts such as loops, conditions and working with random numbers.

In this project we will use:
  • the random module
  • a while loop
  • if conditions
  • input from the user

How the game works

The program randomly chooses a number between 1 and 100.

The player tries to guess the number, and the program gives helpful messages:

  • the number is higher
  • the number is lower
  • you guessed the number

An example of the program running


Guess a number between 1 and 100

Enter a number: 50
The number is lower

Enter a number: 25
The number is higher

Enter a number: 30
You guessed the number!

The program code


import random

secret_number = random.randint(1, 100)

print("Guess a number between 1 and 100")

while True:

    number = int(input("Enter a number: "))

    if number < secret_number:
        print("The number is higher")

    elif number > secret_number:
        print("The number is lower")

    else:
        print("You guessed the number!")
        break

How this code works

  • random.randint() generates a random number
  • while True starts an infinite loop
  • the program checks whether the number is higher or lower
  • the loop ends when the player guesses the number
Try to extend the program by adding the number of attempts or a difficulty level.

Possible improvements to the project

  • limit the number of attempts
  • add difficulty levels
  • show the number of attempts
  • make a graphical version of the game

Next project

How to make the project your own:
1) first run the given code without changes, 2) change one thing and predict what will happen, 3) add at least one feature of your own, 4) write down in a notebook what you changed and why. A work log like that is the basis of a creative programming paper.