Wrie a program that generates a random number 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.
"The program should use a loop that repeats until the user correctly guesses the
random number. Program should count and display number of tries to win the game. (Use for
loop to solve the problem)
import random
attempts = 0
#generate a random value the user needs to guess in range 1 to 100
randomValue = random.randint(0,50)
userValue = -1
while (userValue != randomValue):
#keep asking the user for a guess until the user provides the expected value.
userValue =int(input("Enter value: "))
#If the value is higher than the value to guess, the program will print "Too high";
if (userValue > randomValue):
print("Too high.")
#if it is less, the program will print the message "Too low".
if (userValue < randomValue):
print("Too low.")
attempts+=1
#Once the user enters the expected value, the program will print the number of attempts.
print("The number of tries to win the game: " + str(attempts))
Comments
Leave a comment