Learning python and currently learning the bisection method of solving problem. I'm writing code that should take in a users guess from 0 to 100 and attempt to find that guess using bisection. Here's the code:
answer = raw_input('Please think of a number between 0 and 100')
#I've been using 80 as my test case
low = 0
high = 100
guess = (low+high)/2
while guess != answer:
if guess < answer:
low = guess
else:
high = guess
guess = (low+high)/2
What I've realized is that when my guess < answer is false the else block doesn't execute, so my high number never changes. Why is this happening? Am I overlooking something here?
You need to convert user input to integer (raw_input()
returns a string):
answer = int(raw_input(...))
Comparison fails because you are later comparing an integer to a string (which works in Python2, but would not work in Python3):
>>> 10 < "50"
True
>>> 75 < "50"
True