【问题标题】:Match if-statement conditions with user input sentence (reduce multiple conditions)将 if 语句条件与用户输入语句匹配(减少多个条件)
【发布时间】:2021-01-29 11:03:27
【问题描述】:

我是 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"

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

提前谢谢你!

【问题讨论】:

  • 我认为您需要一个解析器来处理您的输入
  • 一些问题:1) 你的选择会改变吗,比如 1) 我打开盒子,我太好奇了……像那样? 2) 是“公开信”而不是“公开信”吗?
  • @jasonwong。所以用户应该能够输入所有内容。如果选项是“你打开信,你太好奇了!”,用户可以输入:打开信,打开信,打开,信,太好奇。我觉得他们可以用来指代第一个选项的选项是无穷无尽的。我需要确保 Python 识别所有这些选项并将它们分配给正确的选择。所以问他们一个像“你的意思是”........“这样的问题也可以,但我不知道该怎么做。
  • @whoami 抱歉,我不知道解析器是什么以及如何使用它。你也许有一个例子?谢谢!
  • @EstrellaSpaans 这里是与解析相关的链接en.wikipedia.org/wiki/Parsing 也看看这个教程docs.python.org/3/howto/argparse.html

标签: python if-statement input while-loop multiple-conditions


【解决方案1】:

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

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

【讨论】:

  • 谢谢!也许这是一个愚蠢的问题,但 elif 会是什么样子? elif first_choice 在 expected_replies_2 中? (另一个列表)还是 if 语句中的新 if 语句(嵌套)?
  • 是的,elif 中的结构与 if 中的结构相同。
  • 这听起来不太好,因为这需要一长串手动编码的预期回复。更改原文或者原文很长怎么办?
【解决方案2】:

这个呢?它能满足您的需求吗?

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

【讨论】:

  • 你知道第二个选择的结构是什么样的吗?相同的结构?是用elif吗?还是其他 if 语句?
  • 是的,您使用 if-elif-else,并将所有选项放在元组中
猜你喜欢
  • 2016-02-28
  • 2013-12-17
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
相关资源
最近更新 更多