[英]Why do I get a syntax error when trying to test for correct user input?
print ("Hello, and welcome to TEXT RPG!")
name = input("Would you be so kind as to tell us your name?")
print (""+Name+" Is it? What a stupid, stupid name!")
print ("And you, "+Name+" are a stupid, stupid child.!")
print ("However. There is hope for your worthless being yet!")
print ("I will train you and make you less of a worthless being.")
accept1 = input("Do you accept?")
while accept1 = "Yes" "No" "no" "yes" "n" "y":
print ("Alright then! Let us begin!")
else:
print ("That's not an answer you insolent brat!")
accept1 = input("Do you accept?")
由於某種原因,我收到語法錯誤,沒有紅色條。 有人可以幫忙嗎? 我正在使用Python 3.5
有三個錯誤
while accept1 = "Yes" "No" "no" "yes" "n" "y":
您不能在while
語句中使用賦值,而是需要使用==
,而不是=
。 這是語法錯誤的來源:
>>> while accept1 = "Yes" "No" "no" "yes" "n" "y": File "<stdin>", line 1 while accept1 = "Yes" "No" "no" "yes" "n" "y": ^ SyntaxError: invalid syntax
您為字符串"YesNonoyesny"
創建了一個測試,因為Python自動連接連續的字符串。 如果要測試多個可能的值,請使用遏制力測試 。
while
會創建一個無限循環,因為如果測試為真,則您永遠不會在循環中更改accept1
,並且條件將永遠為真。 if
在這里使用,請使用。
這有效:
if accept1 in {"Yes", "No", "no", "yes", "n", "y"}:
因為這會創建一組字符串以再次進行測試,並且如果accept1
的值是該集合的成員,則accept1 in ...
test中的accept1 in ...
為true。
您可以使用str.lower()
使測試更加緊湊和靈活:
if accept1.lower() in {"yes", "no", "n", "y"}:
如果您仍然需要循環,請在循環中提出問題。 只要使其無止境,並使用break
結束它即可:
while True:
accept1 = input("Do you accept?")
if accept1.lower() in {"yes", "no", "n", "y"}:
break
print ("That's not an answer you insolent brat!")
print ("Alright then! Let us begin!")
您有兩個不同的變量:“名稱”和“名稱”。
另外,您的while循環邏輯不正確。 取而代之的是考慮“循環直到獲得可接受的輸入”。 您所擁有的將是任何預期輸入上的無限循環。
while accept1 not in ["Yes", "No", "no", "yes", "n", "y"]:
print ("That's not an answer, you insolent brat!")
accept1 = input("Do you accept?")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.