Home > OS >  How do I incorporate an if statement inside of another if statement?
How do I incorporate an if statement inside of another if statement?

Time:06-23

I'm sort of a beginner at Python; I'm trying to write a text adventure game that prompts the user to explore a room given different options. After the user enters "1," I want the game to enter more choices through another if statement. How should I do that? And if this way is incorrect, what function should I use instead? I've tried putting another if statement in, but that leads to the program producing different results, like outputting a different part of the code instead of the one I want. Here is my code right now:

Name = input("What is your name, visitor?")
print(Name   (", you are being watched. Proceed carefully. A breeze of howling wind enters the room. Within the echo, something reaches out to you and offers a candle. Do you want to light the candle?"))
print("1 for YES")
print("2 for NO")
try:
  Choice = int(input("What do you choose?"))
  print("Choice:", Choice)
except ValueError:
  print("Please input 1 or 2 only...")  
Choice = int(input("What do you choose?"))
if Choice == 1 :
  print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:")
  print("1 for Table")
  print("2 for Drawer")
  print("3 for Lamp")
if Choice == 2 :
  print("You sit in silence,  wondering what to do. Without sight, you're losing options. Eventually, you muster up the courage to stand up. You can't hear your own steps. Fear climbs up your throat. The floor gives way under your feet. You are swallowed by the darkness. GAME OVER.")
  quit()
if not 1:
  print("Please enter either 1 or 2.")
if not 2:
  print("Please enter either 1 or 2")```



CodePudding user response:

There are several issues with this code, but to address your question: nest the if within the outer if:

if Choice == 1 :
    print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:")
    print("1 for Table")
    print("2 for Drawer")
    print("3 for Lamp")
    Choice = int(input("What do you choose?"))
    if Choice == 1:
        # Do table stuff
    elif Choice == 2:
        # Do drawer stuff
    elif Choice == 3:
        # Do lamp stuff
    else:
        # Handle error
  • Related