Number guessing game in Python 3 and C
Most of the geeks from a CS (Computer Science) background, think of their very first project after doing a Programming Language. Here, you will get your very first project and the basic one, in this article.
Task: Below are the steps:
- Build a Number guessing game, in which the user selects a range.
- Let’s say User selected a range, i.e., from A to B, where A and B belong to Integer.
- Some random integer will be selected by the system and the user has to guess that integer in the minimum number of guesses
Explanation 1: If the User inputs range, let’s say from 1 to 100. And compiler randomly selected 42 as the integer. And now the guessing game started, so the user entered 50 as his/her first guess. The compiler shows “Try Again! You guessed too high”. That’s mean the random number (i.e., 42) doesn’t fall in the range from 50 to 100. That’s the importance of guessing half of the range. And again, the user guesses half of 50 (Could you tell me why?). So the half of 50 is 25. The user enters 25 as his/her second guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is shorter, i.e., from 25 to 50. Intelligently! The user guessed half of this range, so that, user guessed 37 as his/her third guess. This time again the compiler shows the output, “Try Again! You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range for user is from 37 to 50, for which the user guessed 43 as his/her fourth guess. This time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as his/her fifth guess. This time the compiler shows the output, “Try Again! You guessed too small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her sixth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the User Guessed the right number which is 42 as his/her seventh guess.
Total Number of Guesses = 7
Explanation 2: If the User inputs range, let’s say from 1 to 50. And compiler randomly selected 42 as the integer. And now the guessing game started. So the half of 50 is 25. The user enters 25 as his/her First guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is shorter, i.e., from 25 to 50. Intelligently! User guessed half of this range, so that, user guessed 37 as his/her second guess. This time again the compiler shows the output, “Try Again! You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range for user is from 37 to 50, for which the user guessed 43 as his/her third guess. This time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as his/her fourth guess. This time the compiler shows the output, “Try Again! You guessed too small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her fifth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the User Guessed the right number which is 42 as his/her sixth guess.
Total Number of Guesses = 6
So, the minimum number of guesses depends upon range. And the compiler must calculate the minimum number of guessing depends upon the range, on its own. For this, we have a formula:-
Minimum number of guessing = log2(Upper bound – lower bound + 1)
Algorithm: Below are the Steps:
- User inputs the lower bound and upper bound of the range.
- The compiler generates a random integer between the range and store it in a variable for future references.
- For repetitive guessing, a while loop will be initialized.
- If the user guessed a number which is greater than a randomly selected number, the user gets an output “Try Again! You guessed too high“
- Else If the user guessed a number which is smaller than a randomly selected number, the user gets an output “Try Again! You guessed too small”
- And if the user guessed in a minimum number of guesses, the user gets a “Congratulations! ” Output.
- Else if the user didn’t guess the integer in the minimum number of guesses, he/she will get “Better Luck Next Time!” output.
Below is the Implementation of the Algorithm:
How to Create a Number Guessing Game in Python?
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.
You should have already guessed the content of this article. And you should probably be familiar with number guessing and looking for a way to built it using Python.
Let’s learn to create a number guessing game from scratch.
Number Guessing Game
The game is simple. The user has to guess the randomly generated number that lies between the range from 1 to 100. That’s it.
But, there is one thing that we have to provide to the users to guess the number. That’s hints. We have to provide a message to the user saying the current guessed number is less than the correct number or the current guessed number is greater than the correct number. So that users will know in which direction they have to go.
We can make it more exciting by adding extra features like maximum number of chances to guess, increasing the range, setting a timer, etc.
Creating the basic working game is mandatory. After it, we can add more features as discussed. So, we are going to create the basic version of the game in this section. And then we will move to add new features.
I want you to try creating the game without blindly copying the code. So, I am going to explain the algorithm first. It will help you to code yourself or understand the code quickly.
Let’s see the algorithm to create the Number guessing game.
Algorithm
Make sure you understand the algorithm before moving to the coding part.
- Define the range of the numbers. By default, it’s 1-100 but you can change it as you prefer.
- Generate a random integer from the above range ( 1-100 ).
- Start the game by displaying the user a message saying “Guess the number from X to Y”. You may update the message as you wish.
- Initialize a variable to 0 to count the total number of chances that the user has taken to guess the number correctly.
- Write an infinite loop.
- Ask the user to guess the number.
- If the current guessed number is equal to the randomly generated number, then congratulate the user with a message as you like. An example would be “-> Hurray! You got it in 5 steps!”.
- Break the loop after congratulating the user.
- If the current guessed number is less than the randomly generated number, then give a message to the user saying “-> Your number is less than the random number” or a custom message having the same meaning.
- If the current guessed number is greater than the randomly generated number, then give a message to the user saying “-> Your number is greater than the random number” or a custom with the same meaning.
- Finally, increment the chances that the user has taken to guess.
You would have got code in your mind after seeing the algorithm. Don’t worry even if you don’t get the complete code. But, make sure you understand the above algorithm.
It’s time to get our hands to work with code. Get into the code without further ado.
Code
Did you try to write the code?
If yes and completed it. It’s great. Check out the code and understand it to add more perspectives to your knowledge.
Don’t worry even if you didn’t write the code. See the below code and understand it. Try to tweak and write it in your own way for better understanding.
import random class NumberGuessingGame: def __init__(self): ## define the range self.LOWER = 1 self.HIGHER = 100 ## method to generate the random number def get_random_number(self): return random.randint(self.LOWER, self.HIGHER) ## game start method def start(self): ## generating the random number random_number = self.get_random_number() print( f"Guess the randomly generated number from to ") ## heart of the game chances = 0 while True: user_number = int(input("Enter the guessed number: ")) if user_number == random_number: print( f"-> Hurray! You got it in step 1 else ''>!") break elif user_number < random_number: print("->Your number is less than the random number") else: print("-> Your number is greater than the random number") chances += 1 ## instantiating and starting the game numberGuessingGame = NumberGuessingGame() numberGuessingGame.start()
There are some things that you understand from the code.
- The range is defined inside the __init__ method so that it can be used across the class methods.
- We can easily change it in one place that changes across the app accordingly.
- There is a separate method to generate the random number which follows the principle of “separate the concerns”. Here, our method has little code, but it might increase in the future.
- Finally, we have used class so that every method that’s related to the game will reside inside it. And it can be easily reused in some other apps.
All the points that are discussed above are related to writing clean code. We should try to write the clean code that you understand even after some X years.
The sample output of the game looks as follows.
$ python number_guessing_game.py Guess the randomly generated number from 1 to 100 Enter the guessed number: 50 -> Your number is less than the random number Enter the guessed number: 75 -> Your number is less than the random number Enter the guessed number: 90 -> Your number is greater than the random number Enter the guessed number: 85 -> Your number is greater than the random number Enter the guessed number: 80 -> Hurray! You got it in 5 steps!
I assume you have Python installed to try the above code.
Extra Feature
We are going to add the maximum number of chances that a user gets to guess the number. If the user doesn’t guess the number within the number of chances, then the user loses.
It’s a simple two-step process. Let’s see the steps.
- Define the maximum number of chances that the user gets to guess the number.
- Check whether the user has chances or not before asking for the input. And end the game if the user is out of given chances.
The following code additional will complete the feature.
if chances == self.MAX_CHANCES: print("-> Phew! You lost the game. You are out of chances")
Now, try the game without guessing the correct number. You should see a similar output as follows.
$ python number_guessing_game.py Guess the randomly generated number from 1 to 100. You have 10 chances to guess. Enter the guessed number: 1 -> Your number is less than the random number Enter the guessed number: 2 -> Your number is less than the random number Enter the guessed number: 3 -> Your number is less than the random number Enter the guessed number: 4 -> Your number is less than the random number Enter the guessed number: 5 -> Your number is less than the random number Enter the guessed number: 6 -> Your number is less than the random number Enter the guessed number: 7 -> Your number is less than the random number Enter the guessed number: 8 -> Your number is less than the random number Enter the guessed number: 9 -> Your number is less than the random number Enter the guessed number: 10 -> Your number is less than the random number -> Phew! You lost the game. You are out of chances
Hurray! we have added an extra feature to our game. It’s not the end though. You can add some more features to make it more engaging to the users. It’s your time now. Go ahead and make it more beautiful :).
Conclusion
We have created a simple number guessing game. Now, it’s your turn to think of games that you were playing when you were young. Make them using programming language and share with your friends. We can digitalize most of our childhood games.
Next, explore Python IDE and online compiler to run Python code.
If you can’t get enough of viral word games, here’s how to do better at Wordle.