【发布时间】: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