简体   繁体   中英

python - checking string for certain words

What I'm trying to do is that, if I ask a question only answerable by Yes and No, I want to make sure that yes or no is the answer. Otherwise, it will stop.

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

Something like:

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

would be the simplest approach (assuming case doesn't matter).

Side-note:

answer = input(">").lower

Is assigning a reference to the lower method to answer , not calling it. You need to add parens, answer = input(">").lower() . Also, if this is Python 2, you need to use raw_input , not input (In Python 3, input is correct).

First:

answer = input(">").lower

should be

answer = input(">").lower()

Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:

if answer == 'no':
    # do this
elif answer == 'yes':
    # do that
else:
    print("Didn't understand you.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM