multiple conditions with while loop in python

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 04:22:39

问题


I am having problems including multiple statements with while loop in python. 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)

回答1:


You need to use 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 '.!?':



回答2:


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 "." and "!" and "?" simultaneously.

You mean:

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

or, more simply,

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


来源:https://stackoverflow.com/questions/26578277/multiple-conditions-with-while-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!