Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,将一个变量重新分配给while循环中的另一个变量_Python_Variables - Fatal编程技术网

在python中,将一个变量重新分配给while循环中的另一个变量

在python中,将一个变量重新分配给while循环中的另一个变量,python,variables,Python,Variables,为什么变量guess没有被更改,我预计low将更改为50,因此newGuess将变为75,对吗?从程序进入而循环的那一刻起,除非重新分配,否则所有变量都已设置 您所做的是重新分配low变量。但是,由于循环中已使用low的旧值包含guess的值,因此需要使用新值重新分配guess。尝试将guess的定义放入第一个循环中,而循环可能是这样。您的问题是guess从未更改。为了改变它,您必须在while循环中声明guess。例如: hint = str low = 0 high = 100 guess

为什么变量guess没有被更改,我预计low将更改为50,因此newGuess将变为75,对吗?

从程序进入
循环的那一刻起,除非重新分配,否则所有变量都已设置


您所做的是重新分配
low
变量。但是,由于循环中已使用
low
的旧值包含
guess
的值,因此需要使用新值重新分配
guess
。尝试将
guess
的定义放入第一个
循环中,而
循环可能是这样。

您的问题是
guess
从未更改。为了改变它,您必须在while循环中声明
guess
。例如:

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
。 在这个示例中,我使
guess
在声明
low
high
guess
后刷新,如果您希望
low
high
声明为
guess
的新值,您可以将声明放在
if
语句之前

如果您有任何问题,请随时在评论中提问。
希望这有帮助。

变量不会因为更改了最初用于声明它们的变量之一而更改。它们是值,而不是公式。
low
会发生变化,但您从未将新值指定给
guess
,因此它不会发生变化。
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