# Python Tutorial - Guess a Number Game

August 1st, 2014 - Software(1 min) 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:

``x = random.randint(1,1000000)``

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

``````n = x + 1  # make sure we get into the loop

while n != x:
n = input(str("Input Number 'n': "))``````

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

``````  if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")``````

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

``````  else:
print("Congrats")
break``````

Here we also exit the loop.

### Multiple Games

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

``````def guess():
x = random.randint(1,1000000)
n = x + 1  # make sure we get into the loop

while n != x:
n = input(str("Input Number 'n': "))
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
print("Congrats")
break``````

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

``````if __name__ == '__main__':
while True:
guess()
again = input(str("Play Again Y/N?: ") == 'N'

# Exit the program if we don't want to try the game again
#
if not again:
break``````

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

``````import random

def guess():
x = random.randint(1,1000000)
n = x + 1  # make sure we get into the loop

while n != x:
n = input(str("Input Number 'n': "))
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
print("Congrats")
break

if __name__ == '__main__':
while True:
guess()
again = input(str("Play Again Y/N?: ") == 'N'

if not again:
break``````

HTH,

Tagged with
All Tags
Share on
Reddit