简体   繁体   中英

Reassigning a variable to another variable in a while loop in python

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

Why is the variable guess not being changed, i'm expecting low to change to 50, therefore newGuess would become 75, correct?

From the moment when your program enters the while loop, all variables are set unless otherwise reassigned.

What you've done is reassigned your low variable. But, because the loop already has the value of guess in it using the old value for low , you would need to re-assign guess again, using the new one. Try putting your definition for guess inside the first while loop, perhaps.

Your problem is that guess is never changed. In order to have it change you would have to put the declaration of guess in the while loop. For instance:

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

This would refresh the variable guess every time the loop loops. In this sample I made it so guess refreshes after you declare low and high as guess , if you wanted low and high to be declared as the new value of guess you would put the declaration before the if statements.

If you have any questions feel free to ask in the comments. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM