在Python中使用while循环的多个条件
我在用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)
相关文章:
- 暂无相关问题
2 个回答
2
这个条件:
(name != ".") or (name != "!") or (name != "?")
总是成立。只有在三个子条件都为假的情况下,它才会变为假。这意味着 name
必须同时等于 "."
、"!"
和 "?"
,这在现实中是不可能的。
你的意思是:
while (name != ".") and (name != "!") and (name != "?"):
或者,更简单地说,
while name not in { '.', '!', '?' }:
4
你需要使用 and
;你希望循环在满足 所有 条件时继续,而不仅仅是一个条件:
while (name != ".") and (name != "!") and (name != "?"):
不过,你不需要使用括号。
这里更好的做法是检查是否包含在某个集合中:
while name not in '.!?':