Guess The Number in Python

As I am working through the tutorials helping me learn Python, I am always thinking of how I could use what I have learnt in the real world.  Unless you have a major project the only thing you can do to use what you have learnt is through mini projects.

A quick Google search later & I found an article on Northwestern University Knight Lab that contained five mini projects to carry out using Python.  Reading the list it took me back to some of the example that I use to carry out whilst at University.

Upon this list was a Guess the Number program and I knew that I could complete this project, even at this early stage of learning.

The best way to start any project is to break down what your program is going to do.   So what do I want from my Guess the Number program?

  • Generate random number
  • Prompt for user input
  • Check the value to see if it higher or lower
  • Inform user the number is correct

This is pretty much the basics required to achieve the goal.  I find it best to create a bare bones version of the final program to check that the basic functions work before expanding upon it.  Even with a basic program like this, you can easily add extras on to make it more user friendly;

  • Check input is a Interger
  • Count the number of attempts (including errors)
  • Check how close the number is to the target (warmer & colder)
  • Tell the user if they guess outside the range
  • Inform the user of how many times it took to guess the number

Now with the knowledge of what I want let’s jump into the code.

Declare Variables & Set Up the Random Number

For this mini project I wanted the user to guess a number between 1 & 50.  I hard coded the lower end but I have created the upper end as a variable.  This will allow me to multiple things such as user input for top number & call the variable for output messages.

from random import random, sample
# Start Count
count = 0
# Fix Range
start = int(1)
end = int(51)
# Generate the random number
number = random()
randomNumber = int(number * end)
# Debug - Show number
print('Debug:',randomNumber)

User Input & Check

The next stage is to prompt the user for a number and then check the value entered is a number.

# Enter a Number
print('**** Guess the Number between',start,'and',end-1,' ****')
# Check value is INT
while True:
    try:
        # Repeat the input if statement is false
        guess = int(input('** Enter a Number:'))
    except ValueError:
        # Not an INT
        print('------------------------------')
        print('I said a number!') # Error
        count += 1 # Increase count
        continue
    else:
        # Statement is True break the loop
        break

Using a while True loop to check if the value entered is a number or not. It will keep prompting the user to enter a number until a number has been entered.

Compare Values

These checks will all happen whilst the guess is not equal (!=) to the target value.

As the point of this program is for the user to guess the random number, it will be best to let them know how close they are.  Before that can happen though a check is in place to see if the number entered is higher than the range.  If so, the user is prompted to enter another number.

The next check it to see how close the entered value is to the target.  The check is set up to display “Getting Warmer” when within 5 of the target.  If not, they will get the “Getting Colder” message.

Note: abs(diff) converts the negative value into a positive

Once this check is completed the next will inform the user if they are higher or lower than the target value.  For each time the user guesses wrong (including the integer check), one is added to a count in the background.

At the end of this while loop is a prompt for the user to enter another number as the current value is not equal to the target.  It will keep doing this until the while statement ( guess != randomNumber) gives the result of False.

# While loop until result is right
while guess != randomNumber:
    print('------------------------------')
    if guess > end-1 :
        count += 1
        print('** The range is 1 to',end-1,'- Try Again!')
    else :
        diff = guess - randomNumber
        # print('Debug: ',diff)
        if abs(diff) < 6 :
            print('** Getting Warmer!')
        else:
            print('** Getting Colder!')
        # Check if number is too high
        if guess > randomNumber :
            print('** Too High - Guess Again')
            count += 1
        # Check if number is too low
        elif guess < randomNumber :
            print('** Too Low - Guess Again')
            count += 1
    # Enter value again & Check
    while True:
        try:
            guess = int(input('** Enter a Number:'))
        except ValueError:
            # Not an INT
            print('------------------------------')
            print('I said a number!')
            count += 1
            continue
        else:
            break

Output Result

Once the correct number has been chosen the program will output a message to the user including the number of times it took to guess.

># When the correct number is picked
count += 1
print('------------------------------')
print('** Well done! The number was',randomNumber)
if count == 1 :
    print('** It only took you',count,'attempt!')
else :
    print('** It only took you', count, 'attempts!')

And that is it. A simple program that explores a few basic functions of Python.
Full source code on my github

Leave a Reply

Your email address will not be published. Required fields are marked *