Implement Guess a Number Game in Python
If you implement a guess-a-number game in Python you will learn many aspects of programming.
- Control flow. The game requires the use of conditional statements and loops to control the flow of the game based on user input and game logic.
- Input and output handling. The game requires the handling of user input and displaying output to the user.
- Random number generation. The game requires generating a random number that the user has to guess, which can teach the programmer how to generate random numbers in their code.
- Debugging. Debugging is an important skill in programming, and implementing a guess-a-number game can help programmers practice debugging by identifying and fixing errors in their code.
- User interface design. While a simple game like guess-a-number may not require a complex user interface, it can still teach the programmer the importance of designing a user-friendly interface for their programs.
- Code organization. The game requires the organization of code into functions and modules, which can help the programmer learn how to write modular and reusable code.
Are you ready?
In this tutorial we will create the classical game: Guess a Number.
The game can be described as follows.
- The computer generates a random number from 1 to 100.
- The user should guess it.
- If the user guesses correctly, it should print how many guesses the user used and the end.
- If the user guesses too low, print it.
- If the user guesses too big, print it.
Are you ready?
Step 1 Get a random number
Python has a standard library random.
An easy way to generate random numbers is by using randrange.
From the docs:
random.randrange(start, stop[, step])
Return a randomly selected element fromPython docs
range(start, stop, step).
If you are familiar with range, this is straightforward to use.
We need a random number from the range of 1 to 100 (both inclusive). Two ways to get that are as follows.
from random import randrange # will import randrange we use # Gives a random integer from the range 1 to 100 (both inclusive) random_number = randrange(100) + 1 # Alternatively random_number = randrange(1, 101)
I prefer the first way of doing it.
Step 2 User interaction and checks
Now you need user interaction to create the guessing game.
A thing to notice is, that you don’t know how many times the user will use to guess the number.
One way to make an iterative approach is to use a while-loop and conditionals.
Another thing we need is to make sure that the input from the user is in the correct range.
from random import randrange random_number = randrange(100) + 1 print("I'm thinking of a number between 1 and 100 (both inclusive)") while True: guess_str = input('What is your guess (1-100): ') guess = int(guess_str) if guess < 1: print('Out of bound') continue if guess > 100: print('Out of bound') continue
WARNING: the above code will continue forever, but we are not done with the project.
What to notice is, we use while True which generates an infinite loop.
We first use continue in the loop, if the user input is not in the expected bound. What continue does, is, it jumps up to the top of the loop and starts all over.
Step 3 The game
The full implementation of the game could be done as follows.
from random import randrange random_number = randrange(100) + 1 guesses = 0 print("I'm thinking of a number between 1 and 100 (both inclusive)") while True: guess_str = input('What is your guess (1-100): ') guess = int(guess_str) if guess < 1: print('Out of bound') continue if guess > 100: print('Out of bound') continue guesses += 1 if guess == random_number: print('Awesome! You guesses it!') print('You used', guesses, 'guesses') break elif guess < random_number: print('Too low') elif guess > random_number: print('Too high')
Notice that we use break to break out of the loop if the user guesses correctly.
Want more Python projects?
This is part of 19 Python Projects and you can create your own MAZE game and improve 4 core programming skills.
Python for Finance: Unlock Financial Freedom and Build Your Dream Life
Discover the key to financial freedom and secure your dream life with Python for Finance!
Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.
Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.
Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.
Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!
Python for Finance a 21 hours course that teaches investing with Python.
Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.
“Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.