Skip to content Skip to sidebar Skip to footer

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:

  1. You make your guess by getting the middle of the low and high values. So you do that with guess = int((high+low)/2)
  2. If the user's number is greater than your guess, then you change your low value to guess+1. If the user's number is lower than your guess, then you change your high value to guess-1.
  3. 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"?"