简体   繁体   English

python中的while循环的多个条件

[英]multiple conditions with while loop in python

I am having problems including multiple statements with while loop in python. 我遇到问题,包括在python中使用while循环的多个语句。 It works perfectly fine with single condition but when i include multiple conditions, the loop does not terminate. 它在单个条件下工作得很好,但是当我包含多个条件时,循环不会终止。 Am i doing something wrong here? 我在这里做错什么了吗?

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)

You need to use and ; 您需要使用and ; you want the loop to continue if all conditions are met, not just one: 如果要满足所有条件,而不仅仅是一个条件,则希望循环继续进行:

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

You don't need the parentheses however. 但是,您不需要括号。

Better would be to test for membership here: 最好在这里测试成员资格:

while name not in '.!?':

This condition: 这种情况:

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

is always true. 永远是真的。 It could only be false of all three subconditions were false, which would require that name were equal to "." 在所有三个子条件均为假的情况下只能为假,这将要求name等于"." and "!" "!" and "?" "?" simultaneously. 同时。

You mean: 你的意思是:

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

or, more simply, 或者,更简单地说,

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

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

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