In this post we will be creating a number guessing game in python, the script will make use of the the random module for which the ‘randint’ function which will return a random integer within our given range.
The game will have the following logic – We start by generating a random integer. The script will take guesses from the user via input and will check if the input is actually a number. If the input is a number and matches the random integer a success message will appear. Should the input be higher than the random integer a message will appear stating so and vice versa.
The source code for this project can be found below.
from random import randint
Number = randint(1,99)
while True:
Guess = input("Enter in your Guess: ")
try:
Guess = int(Guess)
if Guess == Number:
print("Winner - You guessed the right number " + str(Guess)+"\n")
break
if Guess < Number:
print("The number is higher than " + str(Guess)+"\n")
if Guess > Number:
print("The number is lower than " + str(Guess) +"\n")
except ValueError:
print("Please enter a valid number!!!\n")
An example of a games output can be found below.
Enter in your Guess: 50
The number is higher than 50
Enter in your Guess: 60
The number is higher than 60
Enter in your Guess: 80
The number is lower than 80
Enter in your Guess: 70
The number is lower than 70
Enter in your Guess: 65
The number is higher than 65
Enter in your Guess: 68
The number is higher than 68
Enter in your Guess: 69
Winner - You guessed the right number 69
thank for teaching now I am starting to be understanding