简体   繁体   English

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

[英]Python while loop not breaking when conditions are met

I'm just wondering why the loop doesn't break when it meets those conditions and filters over into my other functions? 我只是想知道为什么循环在满足这些条件并过滤到我的其他函数时不中断? I fixed it by doing a while true loop and just breaking in each if statement, but I'd like to know what is wrong with doing this way. 我通过执行一会儿true循环并仅中断每个if语句来修复它,但是我想知道这样做的问题所在。

def main_entrance(): 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

Of course it doesn't break, your condition can never be false 当然不会坏,您的情况永远不会是假的

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

Think about it for a minute, any selection of choice cannot make this expression false. 仔细考虑一下,选择的任何选择都不能使该表达式为假。

choice = 1 选择= 1

False or True or True --> True

choice = 2 选择= 2

True or False or True --> True

choice = 3 选择= 3

True or True or False --> True

Solution

You need to and the conditions together 您需要and条件一起

(choice != 1) and (choice != 2) and (choice != 3)

Or better yet 还是更好

while choice not in [1,2,3]
while (choice != 1) or (choice != 2) or (choice != 3):

This condition is always true. 此条件始终为真。 If your choice variable equals 1, then choice!=1 is false, but choice!=2 is true, so the whole condition is true. 如果您的choice变量等于1,则choice!=1为假,而choice!=2为true,因此整个条件为true。 That is what or means. 这就是or手段。

You could put: 您可以输入:

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

or more succinctly: 或更简洁地:

while choice not in (1,2,3):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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