1

使用 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 中,它会出现“哦”的问题,如果我摆脱它,那么“那是”中的 t 会出现问题,如果我只是摆脱“那太好了” " 下一个 elif 语句的前三个字符有问题。WTF 是错误的,我的 python 代码和 shell 最近运行良好,能够拆分 if 和 elif。但现在突然之间它只是不想。

4

3 回答 3

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

被解析为

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

"a"为真,因此条件始终为真,无论x == "Nod".

相反,您可以使用:

if x in ("Nod", "a", "nod"):
于 2013-07-27T12:33:28.110 回答
1
if x == "Nod" or "a" or "nod":

这总会导致True.

你应该使用

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

或者

if x == "Nod" or x == "a" or x == "nod"
于 2013-07-27T12:32:44.630 回答
0

你的第一个条件:

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."'''
于 2013-07-27T12:34:25.730 回答