Guess the number: a simple python game

guess-the-number-game-in-python.png

In another session of programming with my younger son (a nine years old kid), I proposed to build a program to guess the number.

Dissecting the game

As a first step we have to analyze the algorithm of the game.

Let's think in two friends playing the game.

  • Do you want to play "Guess the number"?
  • Yes, let's play!
  • Ok. I thought a number… Guess it!
  • Hmmm… wait! What is the maximum number?
  • One billion!
  • No, no, no. That's too much. Let's guess numbers between 1 and 100.
  • Ok, ok…. Guess the number!
  • Wait again. Please write down the number to make sure that you are not changing the number.
  • Oh, you're right. DONE. Now, guess the number.
  • 50?
  • No.
  • 70?
  • No
  • 10?
  • No.
  • Hmmmm… Guessing the number is hard! Can you give me a hint?
  • Sure, I'll point if my number is larger or smaller.
  • Great. Let's try again. 50?
  • No, try a smaller number.
  • 42?
  • Yes, CONGRATULATIONS!!!

After this dialogue between two friends we notice the following:

  1. We have to define a range.
  2. Generate a random number within that range, and write it down!.
  3. Trying to guess the number.
  4. Compare our guess with the randomly generated one.
  5. Give the feedback to the guesser.
  6. If the guesser fails to guess, repeat from step 3. Otherwise, the game ends.

The python code

from random import randint
print("Welcome!\nLet's play guess the number")
num_max = int(input("What would be the maximum number?"))
num_comp = randint(1, num_max)

guess = False
steps = 0

while not guess:
    num_usr = int(input("Input a number: "))
    steps += 1
    if num_usr == num_comp:
        guess = True
        print("Congratulations, you guess it!")
        print(f"You achieve it in {steps} steps")
    elif num_usr < num_comp:
        print("Wrong, try with a larger number.")
    elif num_usr > num_comp:
        print("Wrong, try with a smaller number.")

What can be done later?

  • Making sure that the user inputs an integer number.
  • Making sure that the number is in the range!
  • Include our code in a loop that runs while the user wants to keep playing.
  • We could modify our code to consider a maximum number of guessing attempts.

Author: Oscar Castillo-Felisola

Created: 2026-04-02 Thu 14:59