Problem 1 (Single Round Guessing Game) Write a Python program that plays a guess
ID: 3932731 • Letter: P
Question
Problem 1 (Single Round Guessing Game) Write a Python program that plays a guessing game with a user. The game starts with the computer choosing a random integer between 0 and 100 (inclusive). Because we want to be able to test the game easily, the program will print this “secret" value to the screen. The program then continually prompts the user to guess the value until the user guesses the secret number (or enters -1 to give up). After each incorrect guess the game lets the user know if the guess was too high or too low. After a correct guess the game ends and the total number of guesses that user needed is displayed. If the user quit (by entering -1) then the program will also say how many guesses (not including -1) they entered A sample execution of how the game might look when the user guesses the number is provided below Welcome to the guessing game! I have chosen a secret number (and it is 35) Take a guess: 16 Sorry, that is too low. Guess again : 35 Yes, that is right! It took you 2 guessesExplanation / Answer
from random import randint #importing randint to generate random number
secret = randint(0, 100) #random number between 0 and 100
#display stateemnts on the screen to welcome and output the secret
print "Welcome to the guessing game!"
print "-"*50
print "I have chosen a secret number (and it is "+str(secret)+")."
#taking guess as an input from the user
guess = input("Take a guess : ")
#initialise the number of guesses taken to get to the right number
number_of_guesses = 1
#run the loop till the user doesn't enter the correct number
while guess!=secret:
#check if guess less than or greater than secret
if guess<secret:
print "Sorry, that is too low. Guess again : "+str(secret)
else:
print "Sorry, that is too high. Guess again : "+str(secret)
#taking another input from the user
guess = input("Take a guess : ")
#if input = -1, terminating the program
if guess == -1:
break
number_of_guesses += 1
if guess==secret:
print "Yes that is right!"
#printing out the number of guesses
print "It took you "+str(number_of_guesses)+" guesses."
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.