Python Tutorial – Guess a Number Game

Posted by in Software

A while ago I had a problem to solve:

Write a program to guess a number between 1 and 1,000,000 in python.

This is a simple learning program, done in high school or university, particularly when learning a programming language.

The Problem

The problem can be translated in the following parts:

  1. Generate a number between 0 and 1,000,000
  2. When the user enters a number do one of the following:
    • If the number is the one above, notify the user and terminate the program
    • Otherwise, display a hint to the user if the entered number is lower or higher than the generated one and repeat the cycle (allow user to enter another number)
  3. Allow user to play the game again

The Solution

A Game

Let’s write the code allowing the user to play one game. First step is to generate the number to be guessed:

Once we have that, we create the loop that allows user to enter a number:

We check the entered result against x and display the notifications (still in the loop):

We also check the equality (via an else to the same if statement):

Here we also exit the loop.

Multiple Games

If we wrap all of the above code in a function:

we can then just call it in a loop off the main code:

The while loop is quite simple; loop until the user types N and then break out of it.

The if __name__ == '__main__': line ensures the code underneath is executed only when the script it’s written in is called. This allows us to call the guess() function from other scripts/modules without worrying that the loop is executed.

The Full Code

HTH,


A little experiment: If you find this post and ad below useful, please check the ad out :-)