Rashidat Sikiru
Sep 22, 20212 min
In this article, we are going to make a “Guess the Number” game.
How it works
Our games will randomly generate a number between 0 and 30 and the player has to guess the number. If the number entered by the player is less than generated number then the player will be prompted with too low message! And if the number entered by the player is more than generated number then the player will be prompted with too high message! This process will be repeated until the player finds the right number.
Now since we are going to generate a random number and if you've been following past tutorials in the series than you might know what we are talking about here. We are going to import a module that comes pre-installed with our Python, it's called random.
import random
max_num = 30
random_number = random.randint(1, max_num)
Step 4 : Then we will also initialize a guess variable to store the player's answer for comparison.
guess = 0
Step 5 : Now let's create a while loop to keep asking the player until the right number is found. We will keep this loop running until our random_number & guess matches.
while guess != random_number:
pass
Step 6 : so it's time we ask our player to make a guess enter a number to start the game.
while guess != random_number:
guess = int(input(f"Guess the number between 1 &{max_num}: "))
We will also use int() function to covert the number from a string into an integer so that we can compare it to check the answer.
Step 6 : Now we will make use of if conditionals to compare the answer and provide suitable feedback to the player.
while guess != random_number:
guess = int(input(f"Guess the number between 1 &{max_num}: "))
if guess < random_number:
print("Wrong! Too low...")
elif guess > random_number:gfd
print("Wrong! Too high...")
else:
print(f"Thats Right! Random number is {random_number}")
Happy coding !!!