如何解决变量没有更新,而中环(蟒蛇)

问题描述 投票:0回答:4

我想提出的是猜一个数字,你被告知程序,如果数字是高或低的思维程序。我没有收到错误,但我似乎无法更新while循环变量“猜测”,但它仍然等于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.')
python variables while-loop
4个回答
2
投票

IIUC,lowhighguess需要为每个循环更新。您的新guess应该是你的新lowhigh的平均值。

由于是,你的猜测是一样的。例如,如果用户与'higher'响应,guess-low0。除以2仍然0,然后通过添加low,这是guess

你可能会想这样的:

low = guess
guess = (high + low) // 2

high =  guess
guess = (high + low) // 2

1
投票

这是奇怪的,因为有一些错误公式。

    elif use == 'higher':
        low = guess
        guess = (guess-low)//2+low
    elif use == 'lower':
        high = guess
        guess = (high-guess)//2+guess

在这部分,由于low == high == guessguess - low的结果和high - guess将始终为0除以由图2还给出了0。因此,这两条线变得相当于guess = guess

这是因为你重新分配到lowhigh,我相信你的意思是保持猜测范围的上限和下限。

也许你的意思是guess += (high - guess) // 2guess -= (guess - low) // 2


0
投票

你的问题似乎是可变的价值再分配“(我不知道这个词我是法国人),有等于:

=

您必须使用

猜+ =值

要么

猜=猜测+猜测

要么

猜想;猜测 - 猜

要么

猜 - 猜=


0
投票

那是因为你使用的逻辑是错误的。

眼下,正在发生的事情是,

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

更改段将。它的工作!


希望这可以帮助! :)

© www.soinside.com 2019 - 2024. All rights reserved.