【问题标题】:Python while loop not breaking when conditions are met满足条件时Python while循环不会中断
【发布时间】:2014-09-22 13:46:06
【问题描述】:

我只是想知道为什么循环在满足这些条件并过滤到我的其他函数时不会中断?我通过执行 while true 循环并在每个 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

【问题讨论】:

  • This 可能是更好的选择

标签: python


【解决方案1】:

当然不会坏,你的条件永远不会是假的

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

想一想,任何选择都不能使这个表达为假。

选择 = 1

False or True or True --> True

选择 = 2

True or False or True --> True

选择 = 3

True or True or False --> True

解决方案

你需要and条件一起

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

或者更好

while choice not in [1,2,3]

【讨论】:

  • 很好解释和简洁的解决方案!我非常喜欢这个答案!
  • 该死,我怎么没注意到! gah,现在觉得自己很愚蠢。大声笑..是的,我的逻辑很不对劲。编程新手.. 非常感谢一切都说得通!
  • 使用 {1,2,3} 而不是 [1,2,3]。集合查找比列表查找更有效。根据您使用的 Python 版本,可以在编译时而不是运行时创建字面量集(或列表),这样可以提高速度。
【解决方案2】:
while (choice != 1) or (choice != 2) or (choice != 3):

这个条件总是成立的。如果您的choice 变量等于1,那么choice!=1 为假,但choice!=2 为真,因此整个条件为真。这就是or 的意思。

你可以说:

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

或更简洁地说:

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

【讨论】:

  • 使用{1,2,3} 而不是(1,2,3)。集合查找比元组查找更有效。根据您使用的 Python 版本,可以在编译时而不是运行时创建文字集(或元组),这将强调加速。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2013-11-22
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多