if /或功能是否正常工作

时间:2015-11-27 19:38:28

标签: python if-statement

我正在研究一个非常简单的代码,实际上只是从python开始,但是这个问题不断出现。我有这个代码,很多都有类似的结构:

if input() == "no" or  input() == "i said no" or  input() == "I said no." or  input() == "No.":
        print("Okay! Would you like to teach me more words or quit?")

当我运行它时,它可以工作,但我必须输入4次答案才能注册。与其他人一样 - 我必须输入与if函数中的输入一样多的次数。 我试着像这样调整代码:

if (input() == "no" or  input() == "i said no" or  input() == "I said no."  or  input() == "No."):
        print("Okay! Would you like to teach me more words or quit?")

但它仍然没有奏效。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

每次调用input()都意味着python会查找输入。您只需要调用input一次,然后将其另存为变量并进行比较。

answer = input('What is your answer?')
if answer  == "no" or  answer  == "i said no" or  answer  == "I said no." or  answer  == "No.":
    print("Okay! Would you like to teach me more words or quit?")

更好的是,改为:

if answer in ['no','I said no','I said no.','No']:

获得相同的效果