只有当政治家

2024-04-26 21:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python 2.7.5

x = (raw_input)'''What will you Reply?
a. Nod
b. Answer
c. Stare
'''))

if x == "Nod" or "a" or "nod":
    print '''You nod shyly.
"Oh that's Great"'''
elif x == "Answer" or "b" or "answer":
    print '''You answer in a low tone.
"You can speak!"'''
elif x == "Stare" or "c" or "stare":
    print '''you stare blankly, so does the AI.
"Well okay then."'''

当我运行它时,不管我在提示符中输入什么,它只会触发“你害羞地点头”哦,太好了

但是如果我复制这个并粘贴到我的python shell中,它就有一个问题,就是“哦”,如果我去掉它,它就有一个问题,就是“that's”中的t,如果我去掉“that's great”,它就有一个问题,就是下一个elif语句的前三个字符。WTF是错误的,我的python代码和shell最近工作得很好,能够分割if和elif。但现在它突然不想了。你知道吗


Tags: oransweryourawifthatshellnod
3条回答
if x == "Nod" or "a" or "nod":

这总是导致True。你知道吗

你应该使用

if x in ["Nod", "a", "nod"]

或者

if x == "Nod" or x == "a" or x == "nod"
if x == "Nod" or "a" or "nod"

解析为

if (x == "Nod") or ("a") or ("nod"):

"a"是真的,所以无论x == "Nod"与否,条件总是真的。你知道吗

相反,您可以使用:

if x in ("Nod", "a", "nod"):

您的第一个条件:

if x == "Nod" or "a" or "nod":

总是求值为true。请尝试以下代码:

x = raw_input('What will you Reply? a. Nod b. Answer c. Star ')

if x in ["Nod", "a", "nod"]:
    print '''You nod shyly. "Oh that's Great"'''
elif x in ["Answer", "b", "answer"]:
    print '''You answer in a low tone. "You can speak!"'''
elif x in ["Stare", "c", "stare"]:
    print '''you stare blankly, so does the AI. "Well okay then."'''

相关问题 更多 >