当条件满足时,Python while循环不会中断

0 python

我只是想知道为什么循环在满足这些条件并且过滤到我的其他函数时不会中断?我通过做一个真正的循环来修复它,并且只是打破每个if语句,但我想知道这样做有什么问题.

def main_entrance():

print "\n\tYou are in the main entrance. It is a large room with" 
print "\ttwo doors, one to the left and one to the right. There"
print "\tis also a large windy stair case leading up to a second floor."
print "\n\tWhat are you going to do?\n"
print "\t #1 take the door on the left?"
print "\t #2 take the door on the right?"
print "\t #3 take the stairs to the second floor?"

choice = 0

#This seems to be the part that isn't working as I would expect it to.
# I have fixed it and have commented the fix out so that I can understand
# why this way isn't working.

#while True:

while (choice != 1) or (choice != 2) or (choice != 3):


    try:
        choice = int (raw_input ('> '))
        if (choice == 1):
            door_one_dinning_room()
            #break (should not need this break if choice is == 1, 2, 3)

        elif (choice == 2):
            door_two_study()
            #break

        elif (choice == 3):
            stairs_to_landing() 
            #there isn't anything in this function
            #but rather than breaking out from the program once it is 
            # called, but somehow this while loop is still running.

            #break

        else:
            print "You must pick one!"

    except:
        print "Please pick a number from 1-3"
        continue
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 10

当然它不会破坏,你的情况永远不会是假的

(choice != 1) or (choice != 2) or (choice != 3)
Run Code Online (Sandbox Code Playgroud)

想想它一分钟,任何选择的选择都不能使这个表达错误.

选择= 1

False or True or True --> True
Run Code Online (Sandbox Code Playgroud)

选择= 2

True or False or True --> True
Run Code Online (Sandbox Code Playgroud)

选择= 3

True or True or False --> True
Run Code Online (Sandbox Code Playgroud)

你需要and在一起的条件

(choice != 1) and (choice != 2) and (choice != 3)
Run Code Online (Sandbox Code Playgroud)

或者更好

while choice not in [1,2,3]
Run Code Online (Sandbox Code Playgroud)


khe*_*ood 5

while (choice != 1) or (choice != 2) or (choice != 3):
Run Code Online (Sandbox Code Playgroud)

这种情况总是如此.如果你的choice变量等于1,那么它choice!=1是假的,但是choice!=2为真,所以整个条件都是真的.这就是or意味着什么.

你可以把:

while (choice != 1) and (choice != 2) and (choice != 3):
Run Code Online (Sandbox Code Playgroud)

或者更简洁:

while choice not in (1,2,3):
Run Code Online (Sandbox Code Playgroud)