[英]multiple conditions with while loop in python
我遇到問題,包括在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)
您需要使用and
; 如果要滿足所有條件,而不僅僅是一個條件,則希望循環繼續進行:
while (name != ".") and (name != "!") and (name != "?"):
但是,您不需要括號。
最好在這里測試成員資格:
while name not in '.!?':
這種情況:
(name != ".") or (name != "!") or (name != "?")
永遠是真的。 在所有三個子條件均為假的情況下只能為假,這將要求name
等於"."
和"!"
和"?"
同時。
你的意思是:
while (name != ".") and (name != "!") and (name != "?"):
或者,更簡單地說,
while name not in { '.', '!', '?' }:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.