Random Number Guessing Game
Write a program that generates a random number in the range of 1 through 100 and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program
should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” If the user guesses the number, the application
should congratulate the user and then generate a new random number so the game can start over. Optional Enhancement: Enhance the game so it keeps count of the number of guesses that the
user makes. When the user correctly guesses the random number, the program should display the number of guesses.
Random Number Guessing Game Python code:
#Header section of random
import random
#Generates a random number in the range of 1 through 100
#and asks the user to guess what the number.
def playGuessingGame():
randomNum = random.randint(1, 100)
guessCount = 0
#Display “Too high, try again.” If the user’s guess
#is lower than the random number, the program should
#display “Too low, try again.” If the user guesses
#the number, the application should congratulate the
#user and then generate a new random number so the game can start over.
while True:
userChoice = int(input("Guess the number (between 1 and 100): "))
guessCount += 1
if userChoice > randomNum:
print("Too high, try again.")
elif userChoice < randomNum:
print("Too low, try again.")
else:
print("Congratulations! You guessed the number.")
#When the user correctly guesses the random number,
#the program should display the number of guesses.
print("Number of guesses:", guessCount)
break
playGuessingGame()
Executed Output 1:
Guess the number (between 1 and 100):
55
Too high, try again.
Guess the number (between 1 and 100):
22
Too high, try again.
Guess the number (between 1 and 100):
10
Too low, try again.
Guess the number (between 1 and 100):
15
Too high, try again.
Guess the number (between 1 and 100):
13
Congratulations! You guessed the number.
Number of guesses: 5
Executed Output 2:
Guess the number (between 1 and 100):
12
Too low, try again.
Guess the number (between 1 and 100):
10
Too low, try again.
Guess the number (between 1 and 100):
15
Too low, try again.
Guess the number (between 1 and 100):
20
Too low, try again.
Guess the number (between 1 and 100):
25
Too low, try again.
Guess the number (between 1 and 100):
40
Too low, try again.
Guess the number (between 1 and 100):
60
Too low, try again.
Guess the number (between 1 and 100):
70
Too low, try again.
Guess the number (between 1 and 100):
80
Too high, try again.
Guess the number (between 1 and 100):
75
Too low, try again.
Guess the number (between 1 and 100):
76
Too low, try again.
Guess the number (between 1 and 100):
79
Congratulations! You guessed the number.
Number of guesses: 12