繁体   English   中英

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

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

我是 Python 3 世界的新手,我需要一些帮助!

我正在尝试创建一个文本冒险游戏。 用户将有四个选项:

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}!

对于每个选项,我都在 while 循环中使用了 if 语句,因为如果有任何机会输入错误,我想再次提问。 这是前两个选项的示例代码:

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

选项 1 和 2 中提到了一些匹配示例。是否有更好的方法来定义 if 语句中不同的可能字符串条件? 以外:

    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"

如果是这样,我应该怎么做,代码的结构会改变吗? PS,用户应该能够输入其他数字而不是数字 1 或 2。不幸的是,这是游戏的要求。

先感谢您!

那这个呢? 它是否满足您的需求?

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

可能最简单的方法是将每个问题的预期答案放在一个列表中,然后检查一个值是否在该列表中,如下所示:

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