【问题标题】:How to fix variable not updating in while loop (python)如何修复在while循环中不更新的变量(python)
【发布时间】:2019-02-05 04:42:42
【问题描述】:

我正在制作一个程序来猜测您正在考虑的数字,方法是告诉程序该数字是更高还是更低。我没有收到错误,但我似乎无法在while循环中更新变量“guess”,它仍然等于50。教科书给出了higher-lower的公式,所以我不能改变它.

我尝试在 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


    【解决方案1】:

    IIUC、lowhighguess 需要针对每个循环进行更新。您的新guess 应该是您的新lowhigh 的平均值。

    照原样,您的猜测保持不变。例如,如果用户回复'higher',则guess-low0。除以2还是0,再除以low,就是guess

    你可能想要这个:

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

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

    【讨论】:

      【解决方案2】:

      这很奇怪,因为你的公式有问题。

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

      在这部分中,由于low == high == guessguess - lowhigh - guess 的结果将始终为 0。除以 2 也得到 0。因此,这两行都等效于 guess = guess

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

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

      【讨论】:

        【解决方案3】:

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

        现在,正在发生的事情是,

        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
        

        把sn-p改成这个。它会起作用的!


        希望这会有所帮助! :)

        【讨论】:

          【解决方案4】:

          您的问题似乎是变量“值重新分配”(我不确定这个词我是法国人),使用 Equals :

          =

          你必须使用

          猜测+=值

          猜测 = 猜测 + 猜测

          猜测 = 猜测 - 猜测

          猜测 -= 猜测

          【讨论】:

            猜你喜欢
            • 2019-03-05
            • 2020-09-15
            • 1970-01-01
            • 2017-05-19
            • 1970-01-01
            • 2021-11-24
            • 2022-06-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多