hint = str
low = 0
high = 100
guess = (high + low)/2
answer = int(raw_input("Please think of a number between 0 and 100: "))
while (True):
print "Is your secret number " + str(guess) + "?"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
while (hint != "h" and hint != "l" and hint != "c"):
print "invalid option"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
if (hint == "h"):
low = guess
print "newlow: " + str(low)
print "newGuess: " + str(guess)
elif (hint == "l"):
high = guess
elif (hint == "c"):
print "Correct, the answer was " + str(answer)
break
为什么变量猜测没有改变,我期望低变为50,因此newGuess会变成75,对吗?
答案 0 :(得分:4)
从程序进入while
循环开始,除非另行重新分配,否则将设置所有变量。
您所做的是重新分配您的low
变量。但是,因为使用guess
的旧值,循环中已经包含low
的值,您需要再次重新分配guess
,新的那一个。尝试将guess
的定义放在第一个while
循环中。或者
答案 1 :(得分:0)
您的问题是guess
永远不会改变。为了让它发生变化,你必须将guess
的声明放在while循环中。例如:
hint = str
low = 0
high = 100
guess = (high + low)/2
answer = int(raw_input("Please think of a number between 0 and 100: "))
while (True):
print "Is your secret number " + str(guess) + "?"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
while (hint != "h" and hint != "l" and hint != "c"):
print "invalid option"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
if (hint == "h"):
low = guess
print "newlow: " + str(low)
print "newGuess: " + str(guess)
elif (hint == "l"):
high = guess
elif (hint == "c"):
print "Correct, the answer was " + str(answer)
break
guess = (high + low)/2#For instance here
每次循环循环时,这将刷新变量guess
。
在此示例中,如果您希望guess
和low
成为high
,我将guess
和low
声明为high
后进行刷新声明为guess
的新值,您可以将声明放在if
语句之前。
如果您有任何问题,请随时在评论中提问。 希望这会有所帮助。