学习python并且正在学习解决问题的二分法。我正在编写应该吸引用户从0到100猜测的代码并尝试使用二分法找到猜测。这是代码:
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
我意识到的是,当我的猜测&lt;回答是假的else块没有执行,所以我的高数字永远不会改变。为什么会这样?我在这里俯瞰什么吗?
答案 0 :(得分:4)
您需要将用户输入转换为整数(raw_input()
返回一个字符串):
answer = int(raw_input(...))
比较失败,因为您稍后将整数与字符串进行比较(在Python2中有效,但在Python3中不起作用):
>>> 10 < "50"
True
>>> 75 < "50"
True