Creating A Python Program That Guesses A User's "secret Number"?
I'm creating a program that asks you to think of a number from 0 to 100. Then it will guess if it IS 50, lower than 50, or higher than 50. The program will keep guessing with diffe
Solution 1:
Try out this code and see if this is the intended behavior of your program.
print('Hello.')
print('Pick a secret number between 0 and 100.')
print('Is your secret number 50')
low = 0
high = 100whileTrue:
guess = int((low+high)/2)
print('Is your secret number', guess)
a = input('Enter yes/higher/lower:\n')
if a == 'yes':
print('Great!')
breakelif a == 'lower':
high = guess-1elif a == 'higher':
low = guess+1else:
print('I did not understand')
The algorithm goes like this:
- You make your guess by getting the
middle
of thelow
andhigh
values. So you do that withguess = int((high+low)/2)
- If the user's number is greater than your
guess
, then you change yourlow
value toguess+1
. If the user's number is lower than yourguess
, then you change yourhigh
value toguess-1
. - Repeat this process until you eventually get the user's number.
Post a Comment for "Creating A Python Program That Guesses A User's "secret Number"?"