The Number Guessing Game

This is an example mini-program to demonstrate the use of while loops and if .. else statements.

The basic aim is a simple game to ask the user to guess a number between 1 and 10.

Feel free to play around with the program as much as you like.

Note: You will need to set the secret_guess to 4.

1. Number Guessing Game

Planning the program is important. The basic pseudocode for this program is:

pick a random number
while the player hasn’t guessed the number or chosen to exit
    let the player guess
if player guessed correct
    congratulate the player

The program in Python is given below.

# The Number Guessing Game 
import random

# randomly generate a number between 1 and 10
secret_guess = random.randint(1,10)
# to pass the test uncomment this line
# secret_guess = 4

print("Welcome to the Number Guessing Game!")
print("You need to try and guess the number between 1 and 10...")
print("If you wish to exit the game enter 0..")

guess = int(input("Please enter a guess:\n"))

while guess != secret_guess and guess != 0:
  print("That is not correct, please try again.")
  guess = int(input("Please enter a guess:\n"))

if guess != 0:
  print(f"Well done the correct answer is {secret_guess}")

This program generates a random number and then asks the user to input a guess.

The guess is then tested in the while condition and if it is not the correct number and not 0 we repeat the step. If it is the correct number we exit the while.

2. Adding Better Feedback

If you try the program above you will get pretty frustrated by the lack of feedback.

To improve the game we can let the user know if their guess is too low or too high.

This is the subject of exercise 4.5.