簡體   English   中英

python中的while循環的多個條件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM