Guessing Game Lab The local circus is having money trouble, and needs to cut bac
ID: 3690765 • Letter: G
Question
Guessing Game Lab The local circus is having money trouble, and needs to cut back on their performers. The sideshow psychic who tried to guess everyone's weight never did a good job at it anyway, so they've fired him and are asking you to write a program to do the job. The program must randomly generate a number between 1 and 500. That number will be given to the user as the guess for their weight. The user will tell the program is the guess is correct, high, or low. If the guess is correct, display the number of guesses it took to get the right weight. If the guess is high or low, continue making guesses, until the program gets it right. Smart Guessing Your program must guess intelligently. For example, if the program guesses the user's weight at 35, and the user tells the program that guess is low, the program should never guess 35 or below again. The range of guesses will narrow as more guesses are made, until the program has it narrowed down to a single number. Random Numbers To generate random numbers, use the random module from Python. For example, to generate a random number from 1 to 100: import random low = 1 high = 100 number = random.randint(low, high) The import random must only be done once, at the very top of the module. Every time you call random.randint, you get a new random number. Functions You must define functions and use the algorithm techniques that we've been studying to make the code easy to read.
Explanation / Answer
This below Python program will work as specified in given problem statement
1. Limits define 1 to 500
2. User input will ask using prompt
3. Then match the user input with random number generated using randint
See the below code:
import random
BOUNDS = (1, 500)
TRIES_ALLOWED = 5
the_number = random.randint(*BOUNDS)
print(" Welcome to 'Guess My Number'! ")
print("I'm thinking of a number between %d and %d." % BOUNDS)
print("Try to guess it in as few attempts as possible. ")
for tries in range(TRIES_ALLOWED):
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
else:
print("You guessed it! The number was %d" % (the_number))
print("And it only took you %d tries! " % (tries + 1))
break
else:
print("You failed to guess in time! ")
# Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
input("Press the enter key to exit.")
except:
pass
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.