-1
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没有改变,我预计low会变成50,因此newGuess会变成75,对吗?

4

2 回答 2

4

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

你所做的是重新分配你的low变量。但是,由于循环已经guess使用值 for在其中具有值,因此low您需要guess使用新值再次重新分配。尝试将您的定义 forguess 放在第一个while循环中,也许。

于 2013-11-01T17:20:16.893 回答
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这将在每次循环循环时刷新变量。在这个示例中,我在您声明and asguess之后让它如此刷新,如果您想要并被声明为您的新值,您可以将声明放在语句之前。lowhighguesslowhighguessif

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

于 2013-11-01T17:33:28.570 回答