If/else 语句执行不正确
If/else statement executing incorrectly
正在学习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
我意识到,当我的猜测 < 答案为假时,else 块不会执行,所以我的高数永远不会改变。为什么会这样?我在这里忽略了什么吗?
您需要将用户输入转换为整数(raw_input()
returns 字符串):
answer = int(raw_input(...))
比较失败,因为您稍后将整数与字符串进行比较(在 Python2 中有效,但在 Python3 中无效):
>>> 10 < "50"
True
>>> 75 < "50"
True
正在学习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
我意识到,当我的猜测 < 答案为假时,else 块不会执行,所以我的高数永远不会改变。为什么会这样?我在这里忽略了什么吗?
您需要将用户输入转换为整数(raw_input()
returns 字符串):
answer = int(raw_input(...))
比较失败,因为您稍后将整数与字符串进行比较(在 Python2 中有效,但在 Python3 中无效):
>>> 10 < "50"
True
>>> 75 < "50"
True