Home > other >  How to break multiple loops in an if-statement within an if-statement in Python 3
How to break multiple loops in an if-statement within an if-statement in Python 3

Time:06-01

How do I make a loop in an if-statement within an if-statement? I'm busy with How to learn Python 3 the hard way, and so far I know I can do the following:

while True:
print("choose 1st branch")
choice = input()
if choice == '1':
    print('1, now choose second branch')
    while True:
        choice = input("")
        if choice == "2":
            print("2")
            while True:
                choice = input("")
                if choice == "3":
                    print('3')#
                    
                else: #needs to ask for input for choice 3 again
                    print("try again")
        else:print("try again")#needs to ask for input for choice 2 again

ive edited a simpler code example of what im trying to accomplish

CodePudding user response:

Instead of creating a loop everywhere you want to check if the user input is a valid choice, you can extract that "checking if user input is within a valid choices" into a function. Said function will be something like

def get_user_choice(prompt, choices=None):
    while True:
        choice = input(prompt)
        if choices is None:
            # Return the entered choice without checking if it is
            # valid or not.
            return choice
        if choice in choices:
            return choice

        print("unknown choice, try again")

With this new function, we check the validity of the choices first, then after we received the correct input, we then process with the logic for each of the choices.

occu = "ranger"
prompt = "-->"

def get_user_choice(prompt, choices=None):
    while True:
        choice = input(prompt)
        if choices is None:
            # Return the entered choice without checking if it is
            # valid or not.
            return choice
        if choice in choices:
            return choice

        print("unknown choice, try again")


def room1():
    print("you walk into an bare room")
    door = False
    gemstone = False
    hole = False
    monster = False
    rat = False
    trap = False
    occu = "ranger"
    while True:
        print("you see a door infront of you")
        print("do you go left, right or forward?")
        choice = get_user_choice(prompt, ("left", "right", "forward"))
        if choice == "left" and hole == False:
            print("\nDo you \ndodge \nor \nattack?")
            choice = get_user_choice(prompt, ("dodge", "attack"))
            if choice == "dodge" and occu == "ranger":
                trap = True
                rat = True
                print("\nhole \nroom")
                choice = get_user_choice(prompt, ("hole", "room"))

                if choice == "hole" and rat == True:
                    print("you walk up to the hole, you see a faint glitter")

                    print("do you reach your hand in?")
                    print("\nyes \nno")
                    choice = get_user_choice(prompt, ("yes", "no"))

                    if choice == "yes":
                        print("you reach into the whole and pull out a gemstone")
                        print("you put the gemstone in your inventory")
                        print("and go back to the room\n")
                        hole = True
                        gemstone = True
                        choice = True
                    elif choice == "no":
                        print(" you go back to the centre of the room")

Notice that other input also get modified to use this function to check if the choice user selected is valid or not.

CodePudding user response:

The problem is that you are reusing the variable choice, and assigning it to be a boolean value and later on be the input. Try using another variable as well for either the boolean or the input, i.e. proceed.

proceed = False # CREATE VARIABLE PROCEED
while proceed == False: # LOOP WHILE PROCEED IS FALSE
     print("do you reach your hand in?")
     print("\nyes \nno")
     choice = input(prompt)
     if choice == "yes":
         print("you reach into the whole and pull out a gemstone")
         print("you put the gemstone in your inventory")
         print("and go back to the room\n")
         hole = True
         gemstone = True
         proceed = True # CHANGE PROCEED, NOT CHOICE
     elif choice == "no":
         print("You go back to the center of the room")
         # Perhaps assign proceed to be True here as well?
     else: 
         print("unknown choice, try again")

CodePudding user response:

occu = 'ranger'
prompt = "-->"
def room1():
print("you walk into an bare room"
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = 'ranger'
while True:
    print("you see a door infront of you")
    print("do you go left, right or foward?")
    if input(prompt) == 'left' and hole == False:
        print('\nDo you \ndodge \nor \nattack?')
        if input(prompt) == 'dodge' and occu == 'ranger':
            trap = True
            rat = True         
            print("\nhole \nroom")
            if input(prompt) == 'hole' and rat == True:
                print("you walk up to the hole, you see a faint glitter")
                while True:
                    print("do you reach your hand in?")
                    print("\nyes \nno")
                    choice = input(prompt)
                    if choice not in ['yes', 'no']:
                        print("unknown choice, try again")
                        continue # <-- Starts loop over.
                    elif choice == "yes":
                        print("you reach into the whole and pull out a gemstone")
                        print("you put the gemstone in your inventory")
                        print("and go back to the room\n")
                        hole = True
                        gemstone = True
                    else:
                        print(" you go back to the centre of the room")
                    break # <-- Breaks out of loop.
  • Related