Number Guessing Game
In this tutorial, we'll create a simple number guessing game that will have the user guess a number between 1 and 100. Our guessing game will run in the command line, so we are making a command line interface (CLI).
The random
module
In order to generate or random numbers, we need to use the built-in Python module random
. It's used for generating random data, such as random integers and choosing random elements from a list.
Generating Random Numbers
In the random
module, we have a useful function called randint
which takes two parameters (two numbers), a
and b
, and generates a random integer (whole number) between them inclusive. So, for example, I could run randint(5, 10)
and get 5
, 6
, 7
, 8
, 9
, or 10
. This is what we are going to use in our game.
Using randint
We've already discussed how randint
works, so now let's implement our game!
But, before we start using randint
and the random
module, we'll need to import it. We can simply do this by writing
import random
After, we can access the randint
function using random.randint
.
So, therefore, we can generate a random number between 1 and 100 using
num = random.randint(1, 100)
We save the number into the variable num
for use in our game
Implementing The Game
First, we want a while loop for our game, so the user can enter guesses over and over until they get it. And, before the loop, we will add the randint
code.
import random
num = random.randint(1, 100)
while True:
guess = int(input("Guess A Number Between 1 and 100: "))
After, we just need to add some if
statements for the logic:
import random
num = random.randint(1, 100)
while True:
guess = int(input("Guess A Number Between 1 and 100: "))
if guess > num:
print("Your Number Is Too High. Try Again!")
elif guess < num:
print("Your number Is Too Low. Try Again!")
else:
print(f"Correct! The Number Was {str(num)}.")
break
We want to tell the player if they guessed too low, too high, or if they got the number! We can just use some quick if-statements
.
You can also find the code here.
And then, you're done. Congrats!
Extensions
Fun extension ideas:
- Give the user a limited number of guesses
- Add a feature for hints on the number (even or odd, etc.)
- Allow the player to replay after guessing the number
- Add a points system
- Let the user quit in the game
- Make a version of the game using a graphical user interface