Reputation: 21
I have a python program with an if statement. I want to add more choices to the if statement, how do I do it?
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()
I am trying to make this option next:
o2 = input (
"\n" + "[D]ecide to take advantage ..., or T[H]IS HAS YET TO BE WRITTEN?"*)
How should I go about adding more options and choices so that I end up with a story?
Upvotes: 0
Views: 4917
Reputation: 11026
Add a new condition using elif
(else if):
if ...
elif o1 == "D" or o1 == "H":
# your code here
else ...
By the way, you have a syntax error in your conditional statement. Correct it to this:
if o1 == "L" or o1 == "l" or o1 == "Africa" or o1 == "1":
If it makes it easier, look at it this way:
if (o1 == "L") or (o1 == "l") or (o1 == "Africa") or (o1 == "1"):
You should think about the order of operations in your statements. or
has higher precedence than ==
; additionally, the meaning of "L" or "l"
is not what you think it is.
>>> if "L" or "l":
... print("foo")
...
foo
Curious, no? Try some of this stuff out for yourself at the interpreter.
Upvotes: 0
Reputation: 738
There are a couple of good ways to do this, but I would make a class (lets call it "option_node") that uses dictionaries. The class would hold the text of the prompt, then a dictionary that mapped the text options to other option_nodes or a special option node that ends the dialog.
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()
Hope this helps. I can elaborate more if you'd like
Upvotes: 1