Number Guessing Game With Python

number guessing game with python img

LEARN HOW TO BUILD A number guessing game with python

One might be tempted to ask “What’s the importance of building this number guessing game with python?” Well..It’s a good question, especially for beginners in python. This short tutorial and other similar tutorials is what develops your python coding skills, you can read, listen or watch tutorials for hours or even months, if you don’t build a project or at least challenge yourself with short challenges like this, you’d never develop the needed skills.

However, don’t just run the code, challenge yourself by coding your own number guessing game with python, but with a different approach, trust me this number guessing game with python has been built with different approaches. The most important thing is that it gives off the expected output. Who knows? your own approach might even end up being better than mine.

Without further ado, let’s dive into this short and interesting tutorial. If you are a beginner in python then this tutorial will surely help your learning.

ANY REQUIRED PRIOR KNOWLEDGE?

The difficulty rate for this particular guessing game with python is beginner/medium and what’s required is not that much, once you already know the basics of python like lists, python scope, indentation, input, while loop, try and except, and a few other concepts, then this should be fun..


WHAT YOU WILL LEARN IN number guessing game with python

  • How to use the randint from random library.
  • Python operators
  • How to get information from user and assign them to variables
  • Using of while loops
  • How to eliminate and control possible errors from user’s end instead of showing the usual error code.

NOW LET’S CODE..



# let's import the necessary library, we'll use randint to generate random numbers
from random import randint


#let's set up some variables for the game
diff_level = 0
diff_choice = ''
diff_response = ['easy', 'hard']
hidden_num = randint(1,200)


#let's make sure the user is entering the required string for difficulty level to aviod error
#let's also get user preferred difficulty level as well
while diff_choice not in diff_response:
    diff_choice = input('Hey! choose a difficulty level, please type in either "easy" or "hard" only:\n').lower()
if diff_choice == 'easy':
    diff_level = 15
else:
    diff_level = 5
    

#let's communicate to the user his/her choice and how the game works
print(f'Great! You have chosen {diff_choice}, which means you can guess up to and not more than {diff_level} times, let the game🤩 begin! ')
# print(f'the hidden number was {hidden_num}')


#let's make sure the user enters the required input and also capture the user input
guessed_num = int(input('A number between 1 and 200 has been marked, guess the marked number🤔:\n'))
    


#let's keep running the game until the user chances finishes or until the user guesses the marked number right
while guessed_num != hidden_num:
    diff_level -= 1
    if diff_level == 0:
        print(f'Your chances are now {diff_level}, you have exhausted all your chances, the marked number was {hidden_num} 🙁GAME OVER!')
        break
    
    
    if guessed_num > hidden_num:
        guessed_num = int(input(f'The number: {guessed_num} is incorrect and higher than the marked number, you now have {diff_level} chances left \n Guess again:'))
        
    if guessed_num < hidden_num:
        guessed_num = int(input(f'The number: {guessed_num} is incorrect and less than the marked number, you now have {diff_level} chances left \n Guess again:'))
       
    
    
else:
    print(f'Wow! You are awesome! 😍 You guessed right, the marked number was actually {hidden_num}')
    

SO EXPECTED OUTPUT WILL BE SOMETHING LIKE THE RESULT BELOW:

Hey! choose a difficulty level, please type in either "easy" or "hard" only:
hard
Great! You have chosen hard, which means you can guess up to and not more than 5 times, let the game🤩 begin! 
A number between 1 and 200 has been marked, guess the marked number🤔:
30
The number: 30 is incorrect and less than the marked number, you now have 4 chances left 
 Guess again:50
The number: 50 is incorrect and less than the marked number, you now have 3 chances left 
 Guess again:100
The number: 100 is incorrect and higher than the marked number, you now have 2 chances left 
 Guess again:73
The number: 73 is incorrect and less than the marked number, you now have 2 chances left 
 Guess again:75
The number: 75 is incorrect and less than the marked number, you now have 1 chances left 
 Guess again:80
Your chances are now 0, you have exhausted all your chances, the marked number was 86 🙁GAME OVER!

BONUS CODE

Meanwhile on the code above we have tried to eliminate some possible bugs but however in as much it was mentioned on line 28 that it must be a number (integer) between 1 and 200, someone might still mistakenly enter something else, due to typo error or some other reasons, so to eliminate that make use of try and except to capture and control that error.

You might also want to wrap the number checking in a function and apply the try-and-except on the function, then call the function while the guessed_num is invalid. In case you have forgotten how to use try and except see code below:

# Bonus: Use the code below if you'd like to catch and control the error while getting integer variable from user

while True:
    try:
        guessed_num = int(input('A number between 1 and 200 has been marked, guess the marked number:\n'))
    except:
        print('Please enter an integer only, any number between 1 and 200')
        continue
    else:
        print('Hmm, nice first time try\n')
        break

CODE EXPLAINED..

A good code need not be explained, one of the best attributes of a good code is “readable”, so why the explanation right? well we still have to put up a few words for total beginners.

Most of the lines are readable and comprehensive but i’ll just pick a few lines and explain them.

At line 2 we imported randint from random library which we used in generating random numbers between 1 and 200 so that the marked number changes each time the user runs the code afresh.

At line 14 we had to use that while loop to force the user to select from the two options we gave, as long as the user selects something else the loop will keep running until the user gets it right.

From line 33 we had to use a while loop to keep asking the user for the marked number until the user gets it right, and also minus 1 from the user chances each time they try. In case you don’t understand why the code was structured the way it is, you should google or learn how python code executes, the order of execution, loops and scope.

If you happen to run into any puzzle don’t hesitate to write me, or leave a comment at comment section.

You may also stay connected with our updates on our telegram channel.

To run and see this code in action click here. In case you are also on replit, you can also fork the code and play around with it.

We might actually have subsequent number guessing game with python tutorial or edit this one in future which might have a higher difficulty level, so remember to stay tuned by signing up to our newsletter.

🤞 Don’t miss the tips!

We don’t spam! Read more in our privacy policy

Geoff

Geoff is a software engineer, web content specialist, tech private trainer and an IT virtual assistant.

This Post Has One Comment

Leave a Reply