简体   繁体   中英

Python: Why Does my while loop keep looping

def guess():
    while True:
        try:
            guess = raw_input("Guess your letter")
            if len(guess) != 1 or guess.isdigit() == True:
                print "Please guess again"
            if len(guess) == 1 and  guess.isdigit() == False:
                guessed.append = guess
                return guess
                break
        except StandardError:
            pass

print guess()

this loop keeps repeating no matter what value I put in the raw input. Why???

Because guessed.append = guess wil raise an error every time len(guess) == 1 and guess.isdigit() == False is True and then the control will go to the except block which is going to restart the loop again.

If you've defined guessed somewhere in your code then I think you probably wanted to do this:

guessed.append(guess)

Otherwise define guessed first.

Every time you try to execute the line guessed.append = guess you raise a StandardError , so the line telling you to return guess is never executed.

To fix it you should define guessed outside the function, and correct the line to guessed.append(guess) .

Also note that the line break right after return guess would never be executed even if you fixed this bug.

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