简体   繁体   English

如何在 Python 3 中的 if 语句中打破 if 语句中的多个循环

[英]How to break multiple loops in an if-statement within an if-statement in Python 3

How do I make a loop in an if-statement within an if-statement?如何在 if 语句中的 if 语句中创建循环? I'm busy with How to learn Python 3 the hard way , and so far I know I can do the following:我正忙于How to learn Python 3 hard way ,到目前为止我知道我可以做到以下几点:

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我编辑了一个更简单的代码示例,说明我试图完成的事情

The problem is that you are reusing the variable choice , and assigning it to be a boolean value and later on be the input.问题是您正在重用变量choice ,并将其分配为布尔值,然后再作为输入。 Try using another variable as well for either the boolean or the input, ie proceed .尝试对布尔值或输入使用另一个变量,即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")
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.

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.请注意,其他输入也被修改以使用此功能来检查用户选择的选项是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM