我很好奇为什么下面的语法块会根据代码中“ans”的位置对变量“ans”进行不同的处理。在第一个例子中,“ans”根据用户输入正确递增/递减。在第二个中,尽管用户输入,“ans”仍保持等于原始值(在这种情况下为50)。变量“低”和“高”在循环之外但仍然保存循环中的值,而“ans”在循环之外而不是。感谢帮助。
1
low = 0
high = 100
print("Please think of a number between 0 and 100!")
while True:
ans = int((high + low)/2)
print("Is your secret number", str(ans), "?")
x = input("Enter h if too high, l if too low, or c if correct: ")
if x == "l":
low = ans
elif x == "h":
high = ans
elif x == "c":
print("Game over. Your secret number was: ", ans)
break
else:
print("Sorry I did not understand your input.")
x = input("Enter h if too high, l if too low, or c if correct: ")
2
low = 0
high = 100
ans = int((high + low)/2)
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number", str(ans), "?")
x = input("Enter h if too high, l if too low, or c if correct: ")
if x == "l":
low = ans
elif x == "h":
high = ans
elif x == "c":
print("Game over. Your secret number was: ", ans)
break
else:
print("Sorry I did not understand your input.")
x = input("Enter h if too high, l if too low, or c if correct: ")