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

时间:2013-11-01 17:15:41

标签: python variables

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,对吗?

2 个答案:

答案 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。 在此示例中,如果您希望guesslow成为high,我将guesslow声明为high后进行刷新声明为guess的新值,您可以将声明放在if语句之前。

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