[英]python - checking string for certain words
我想做的是,如果我問一個只能由“是”和“否”回答的問題,我想確保答案是“是”或“否”。 否則,它將停止。
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
就像是:
if word.lower() in ('yes', 'no'):
將是最簡單的方法(假設大小寫無關緊要)。
邊注:
answer = input(">").lower
正在分配對lower
方法的引用以answer
,而不是調用它。 您需要添加括號, answer = input(">").lower()
。 另外,如果這是Python 2,則需要使用raw_input
而不是input
(在Python 3中, input
是正確的)。
第一:
answer = input(">").lower
應該
answer = input(">").lower()
其次, len(answer) > 1
對於"no"
和"yes"
都是正確的(就此而言,大於一個字符的任何值)。 elif
塊將永遠不會被評估。 在不顯着修改當前代碼邏輯的情況下,您應該執行以下操作:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.