【问题标题】:multiple conditions with while loop in pythonpython中带有while循环的多个条件
【发布时间】:2014-12-22 02:00:21
【问题描述】:

我遇到了问题,包括在 python 中使用 while 循环的多个语句。它在单个条件下工作得很好,但是当我包含多个条件时,循环不会终止。我在这里做错了吗?

name = raw_input("Please enter a word in the sentence (enter . ! or ? to end.)")

final = list()

while (name != ".") or (name != "!") or (name != "?"):
    final.append(name)
    print "...currently:", " ".join(final)
    name = raw_input("Please enter a word in the sentence (enter . ! or ? to end.)")
print " ".join(final)

【问题讨论】:

    标签: python while-loop multiple-conditions


    【解决方案1】:

    你需要使用and;如果满足所有条件,您希望循环继续,而不仅仅是一个:

    while (name != ".") and (name != "!") and (name != "?"):
    

    但是你不需要括号。

    最好在这里测试会员资格:

    while name not in '.!?':
    

    【讨论】:

      【解决方案2】:

      这个条件:

      (name != ".") or (name != "!") or (name != "?")
      

      总是正确的。它只能是所有三个子条件都为假的假,这将要求 name 等于 ".""!""?" 同时。

      你的意思是:

      while (name != ".") and (name != "!") and (name != "?"):
      

      或者,更简单地说,

      while name not in { '.', '!', '?' }:
      

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 2015-02-14
        • 2015-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        相关资源
        最近更新 更多