# Guess user number between 0 and 100 (Binary Search)

I am at the beginning of learning python and one of my homeworks (in chapter regarding loops) where to write a code that would guess user number between 1 - 100.

I believe I used algorithm called binary search.

# Introduction
print('\nThink about a number between 0 - 100 and let me guess which is it.',
'\n\nI will ask you whether my guess is lower or higher than your number',
'\nIndicate "l" if lower than your number',
'"h" if higher than your number and',
'"e" if my guess is correct.'

# Algorithm
count = 0
lborder = 0
hborder = 100
guess = 50

while True:
answer = input('Is your number higher, lower or equal to ' + str(guess) + ':')
hborder = guess
guess = round((lborder + guess)/2)
lborder = guess
guess = round((hborder + guess) / 2)
break
else:
print('Unrecognizable answer. Use: "l", "h", "e"')
count += 1

print('\nHooray! It took me', count, 'to guess your number.', sep=' ')
input('\nPress Enter to Exit.')


My question is basically whether there is a better algorithm for finding those numbers (quicker). Also do you have any other comments about my code.

• The binary search algorithm is optimal for this problem, assuming that users' choices are evenly distributed in the 0..100 range. Commented Jun 14, 2019 at 10:07

Your calculation of count is incorrect in two ways: 1. You don't count your last guess; 2. You count invalid user input.

I would separate the input validation from the input processing. And I would add some logic to handle user input that leads to trying the same guess repetitively, for this the user has to lie, but who guarantees us they won't?

You should use:

guess = int((hborder + guess) / 2)


instead of guess = round((hborder + guess) / 2) for correct computation.

• Could you also explain why this would be the correct way? Commented Jun 14, 2019 at 4:24
• That's simply wrong - we want to round up in that case. It's the lborder line that needs to round down. It would be more efficient to simply use integer division, though: (lborder + guess) // 2 and (hborder + guess + 1) // 2. Commented Jun 14, 2019 at 10:05