简体   繁体   中英

Match if-statement conditions with user input sentence (reduce multiple conditions)

I am new to the world of Python 3, and I need some help!

I am trying to create a text adventure game. The user will have four options:

1) You open the letter, you are too curious! 
2) You do not want to miss class, so you put it in your backpack. 
3) You think this is not real and quite ridiculous, so you throw it in the bin. 
4) You definitely want to open this together with {Friend_name}!

For each option, I have used if-statements within a while loop because if there is by any chance a wrong input, I want to ask the question again. This is the sample code of the first two options:

while True:
    first_choice = input(prompt ="What is your choice?  - ")

    if first_choice == "1" or first_choice == "open" or first_choice == "letter" or first_choice == "open letter" or first_choice == "are too curious" or first_choice == "curious"
        print(f"""
        You call {Friend_name over}, who was waiting for you in the hall. 
        You rip the letter open and....""")
        break

   elif first_choice == "2"or first_choice == "do" or or first_choice == "not" or or first_choice == "miss" or or first_choice == "class" or or first_choice == "miss class" 
        print("Class turned to be very boring" )
        break

A few of the matching examples are mentioned for options 1 and 2. Is there a better way to define the different possible string conditions within the if-statement? Other than:

    if first_choice == "1" or first_choice == "open" or first_choice == "letter" or 
    first_choice == "open letter" or first_choice == "are too curious" or first_choice 
    == "curious"

If so, what should I do, and would the structure of the code change? PS, the user should be able to put in something else than just numbers 1 or 2. That is a requirement of the game, unfortunately.

Thank you in advance!

What about this? Does it fix your needs?

if first_choice in ("1", "open", "letter", "open letter", "are too curious", "curious"):
    #process code

Probably the easiest way to do this would be to for each of questions put expected answers in a list and then check whether a value is in that list like so:

expected_replies_1 = ['1', 'open', 'letter', 'open letter',]
first_choice = input(prompt ="What is your choice?  - ")

if first_choice in expected_replies_1:
    do stuff...

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