Answer to Question #285042 in Python for Vivek

Question #285042

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)


1
Expert's answer
2022-01-05T08:13:28-0500
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))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS