Python,如何在if语句中添加更多选项
我有一个带有if语句的python程序。我想在if语句中添加更多选项,我该怎么做Python,如何在if语句中添加更多选项,python,if-statement,Python,If Statement,我有一个带有if语句的python程序。我想在if语句中添加更多选项,我该怎么做 def start(): print ("A Wise man once said ...") o1 = input("\n" + "[L]ook to the poverty of Africa ... [T]HIS HAS YET TO BE WRITTEN") if o1 == "L" or "l" or "Africa" or "1": print
def start():
print ("A Wise man once said ...")
o1 = input("\n" +
"[L]ook to the poverty of Africa ... [T]HIS HAS YET TO BE WRITTEN")
if o1 == "L" or "l" or "Africa" or "1":
print ("\n" + "You decide only a radical solution is viable...")
else:
print ("THIS IS NOT WRITTEN YET")
def menu ():
print ("Menu\n")
print ("(1)Start")
print ("(2)Exit\n\n")
choice = (input('>>'))
if choice=="1":
start()
if choice=="2":
quit()
menu()
我正在尝试下一步的选择:
o2 = input (
"\n" + "[D]ecide to take advantage ..., or T[H]IS HAS YET TO BE WRITTEN?"*)
我应该如何添加更多的选项和选择,以便最终得到一个故事?有几种好方法可以做到这一点,但我会创建一个使用字典的类(我们称之为“选项节点”)。该类将保存提示的文本,然后是一个将文本选项映射到其他选项节点的字典,或者是一个结束对话框的特殊选项节点
class option_node:
def __init__(self, prompt):
self.prompt = prompt
self.options = {}
def add_option(self, option_text, next_node):
self.options[option_text] = next_node
def print_prompt(self):
print(prompt)
def select_input(self):
for each in self.options:
print(each)
while(True)
user_input = input(">>")
if self.options.get(in):
return self.options.get(in)
def main():
nodes = []
nodes.append(option_node("Welcome"))
nodes.append(option_node("Stay Awhile"))
nodes.append(option_node("That's fine, I don't like you much either"))
nodes[0].add_option("Hello friend", nodes[1])
nodes[0].add_option("Hello enemy", nodes[2])
nodes[1].options = None
nodes[2].options = None
current_node = nodes[0]
while current_node.options is not None:
current_node.print_prompt()
current_node = current_node.select_input()
希望这有帮助。如果您想使用
elif添加一个新条件,我可以详细说明(否则,如果):
顺便说一下,您的条件语句中有语法错误。请将其更正为:
if o1 == "L" or o1 == "l" or o1 == "Africa" or o1 == "1":
如果这样做更容易,请这样看:
if (o1 == "L") or (o1 == "l") or (o1 == "Africa") or (o1 == "1"):
您应该考虑语句中的操作顺序<代码>或
的优先级高于=
;此外,“L”或“L”
的含义与您想象的不同
>>> if "L" or "l":
... print("foo")
...
foo
好奇,不是吗?在口译员处自己尝试一下这些东西。您是否使用了
菜单
功能?如果没有,我认为你的观点是正确的——你可以将一系列选项以及用户选择该选项时要执行的可调用项传递到菜单中。这不是语法问题,而是程序的结构问题。你只是在学习编程吗?如果是这样的话,我建议参加一些免费的在线课程(现在很多,只有几个平台:khan academy、Coursera、Udacity、edX等)或Codeacademy,他们有一门Python课程。在相关说明中,OP可能想看一看,如果能详细介绍,我将不胜感激。谢谢你的时间:-)我又加了一点。我还没有测试过这个示例,但它应该演示如何使用我创建的类来构建某种类型的会话流。
>>> if "L" or "l":
... print("foo")
...
foo