[英]How to fix variable not updating in while loop (python)
我正在编写一个程序,通过告诉程序该数字是高还是低来猜测您正在考虑的数字。 我没有收到错误,但是我似乎无法在while循环中更新变量“ guess”,它仍然等于50。教科书给出了高-低的公式,所以我无法更改。
我试过在while循环内移动变量,但是仍然不会更新。
print('Hello.')
print('Pick a secret number between 0 and 100.')
low = 0
high = 101
guess = 50
while True:
print('Is your secret number',guess)
use = input('Enter yes/higher/lower:\n').lower()
if use == 'yes':
print('Great!')
break
elif use == 'higher':
low = guess
guess = (guess-low)//2+low
elif use == 'lower':
high = guess
guess = (high-guess)//2+guess
else:
print('I did not understand.')
需要为每个循环更新IIUC, low
, high
和guess
。 您的新guess
应该是你的新的平均值low
和high
。
照原样,您的猜测保持不变。 例如,如果用户以'higher'
响应,则guess-low
值为0
。 除以2
仍为0
,然后乘以low
,这是guess
。
您可能想要这样:
low = guess
guess = (high + low) // 2
和
high = guess
guess = (high + low) // 2
太奇怪了,因为您的公式有问题。
elif use == 'higher':
low = guess
guess = (guess-low)//2+low
elif use == 'lower':
high = guess
guess = (high-guess)//2+guess
在这一部分中,由于low == high == guess
, guess - low
和high - guess
low == high == guess
的结果始终为0。除以2也会得到0。因此,两行都等同于guess = guess
。
这是因为您要重新分配到low
和high
,我相信您的意思是保持猜测范围的下限和上限。
也许您的意思是guess += (high - guess) // 2
和guess -= (guess - low) // 2
?
您的问题似乎是带有“等于”的变量“值重新分配”(我不确定这个词我是法语):
=
你必须使用
猜+ =值
要么
猜=猜+猜
要么
猜=猜-猜
要么
猜-=猜
那是因为您使用的逻辑是错误的。
现在发生的是
low = guess
guess = (guess - low) // 2 + low
low = guess
上面的陈述等同于,
guess = (guess - guess) // 2 + low
# guess = 0 + low
# guess = low
同样,对于高
high = guess
guess = (high - guess) //2 + guess
high = guess
上面的陈述等同于,
guess = (high - high) // 2 + guess
# guess = 0 + guess
# guess = guess
这就是为什么它总是停留在50
。
它起作用的实际逻辑如下,
elif use == 'higher':
low = guess
guess = (guess + high) // 2
elif use == 'lower':
high = guess
guess = (guess + low) // 2
将代码段更改为此。 会工作的!
希望这可以帮助! :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.