简体   繁体   English

将if语句条件与用户输入的句子匹配(减少多个条件)

[英]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!我是 Python 3 世界的新手,我需要一些帮助!

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.对于每个选项,我都在 while 循环中使用了 if 语句,因为如果有任何机会输入错误,我想再次提问。 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?选项 1 和 2 中提到了一些匹配示例。是否有更好的方法来定义 if 语句中不同的可能字符串条件? 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. PS,用户应该能够输入其他数字而不是数字 1 或 2。不幸的是,这是游戏的要求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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