Reputation: 145
I am a very beginner in Python, I want to write a number guessing program in which the user thinks of a number which the computer has to guess. I wrote this it works but there is this problem: say my secret number is 13. The computer says 45, I enter 'h', then it says a number in range of (0, 45), for example it says 10, after I enter 'l' I don't want it to say a number over 45 (the number I said was too high!) and vice versa about the low number.
import random
print('Please think of a number between 0 and 100!')
input('''Press Enter once you've thought of one...''')
guess = random.randint(0,100)
print('Is your secret number', guess, '?'
'''\nEnter 'h' to indicate the guess is too high'''
'''\nEnter 'l' to indicate the guess is too low'''
'''\nEnter 'c' to indicate the guess is correct''')
hlc = input()
while hlc <= 'h' or 'l' or 'c':
if hlc == 'h':
guess -= 1
guess = random.randint(0, guess)
print('Is your secret number', guess,'?')
hlc = input()
elif hlc == 'l':
guess += 1
guess = random.randint(guess, 100)
print('Is your secret number', guess,'?')
hlc = input()
elif hlc == 'c':
print('Game over. Your secret number was', guess, '!')
break
Upvotes: 1
Views: 73
Reputation: 75714
You should track the highest and lowest numbers your user has rejected so far. Something like the following:
lowest_guess = 100
highest_guess = 100
while ... :
guess = random.randint(lowest_guess, highest_guess)
...
if hlc == 'h':
highest_guess = guess
elif hlc == 'l':
lowest_guess = guess
Upvotes: 1