python - 检查某些单词的字符串

时间:2015-12-02 02:18:03

标签: python

我想要做的是,如果我问一个问题只能回答是和 不,我想确保答案是肯定还是否定。否则,它会停止。

 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.")

2 个答案:

答案 0 :(得分:1)

类似的东西:

if word.lower() in ('yes', 'no'):

将是最简单的方法(假设情况无关紧要)。

侧面说明:

answer = input(">").lower

lower方法的引用分配给answer,而不是调用它。您需要添加parens,answer = input(">").lower()。另外,如果这是Python 2,则需要使用raw_input,而不是input(在Python 3中,input是正确的。)

答案 1 :(得分:1)

首先:

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.")