【问题标题】:Breaking out of loop - Python跳出循环 - Python
【发布时间】:2020-05-21 03:26:38
【问题描述】:

我尝试过在 SO 上进行谷歌搜索和搜索,但我无法弄清楚为什么我在倒数第二行的中断没有退出 while 循环。更好的是,我无法弄清楚为什么循环也没有继续。我的目的是让用户有可能在最后一个选择之后前往主菜单(基本上是 menuchoice 的 while 循环(这是我在此处粘贴的一个循环)。

有什么建议吗?先感谢您。感觉好像我错过了一些重要的东西。

#this is going to show how many exercise weapons you need for next magic level
if menuchoice == "4":
    #these functions returns the amount of magic wands/rods that is needed to be spent for next magic level
    print("Select vocation")
    print("Press P for Royal Paladin")

    #ask user to input vocation:
    while True:
        vocationchoice = input()
        if vocationchoice == "P" or vocationchoice == "p":
            #ask user to input magic level for paladin
            num1 = float (input("Enter your magic level: "))

            #ask for own training dummy
            print("Do you have your own exercise dummy? Type Y for yes and N for no.")
            while True:
                trainingdummy = input()
                if trainingdummy == "y" or trainingdummy == "Y":
                    #list the different exercise weapons
                    print("Select exercise weapon:")
                    print("1. Training rod")

                    #loop, where we ask user to input what exercise weapon they want to calculate
                    while True:
                        while True:
                            weaponchoice = input()
                            if weaponchoice == "q":
                                sys.exit() #quit the program
                            if weaponchoice == "1" or weaponchoice == "2" or weaponchoice == "3" or weaponchoice == "f":
                                break #break out of the input loop

                        #User choice
                        if weaponchoice == "1":
                            print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")

                if trainingdummy == "n" or trainingdummy == "N":
                    #list the different exercise weapons
                    print("Select exercise weapon:")
                    print("1. Training rod")

                    #loop where ask user to input what exercise weapon they want to calculate
                    while True:
                        weaponchoice = input()
                        #User choice
                        if weaponchoice == "1":
                            print("The amount of training rods needed for next magic level is " + str((nextmaglvlpal(num1))) + ".")

                        elif weaponchoice == "f":
                            break

                        print("\nGo to main menu? Press F.")

【问题讨论】:

  • 你说的是第一个break语句还是最后的第二个?
  • 也许,您可以使用布尔值 variablevar = False 代替 break,而不是 break
  • @LouisLac 最后一个。它什么也没做。如果我删除那个中断,我是否应该能够再次按“1”并获得相同的结果?如果它在那个循环内?
  • 预期的行为是当按下“f”返回主菜单时的break语句,例如退出所有之前的while循环?现在,当按下“f”时,您的代码将留在训练虚拟“选择循环中。
  • 这是预期的行为,是的。但同样,如果我删除最后一行的 break 语句,我应该能够再次按“1”,它应该会给我结果。第一次按“1”后,它会停留在那里,就像它不是 while 循环的一部分一样。很奇怪。

标签: python while-loop break


【解决方案1】:

首先,您应该在input() 命令中打印内容,因为它会在意图中被清除:input("Text to display")

其次,如果你想退出到主菜单,你需要打破每一个嵌套循环。在这里你只打破最内层的循环。

在 Python 中没有 goto 指令或命名循环,您可以使用标志。当 used 按“F”时,标志设置为 true,然后在每个外部嵌套循环的开头使用该标志来中断它们。它可能看起来像这样:

while True: # This is your menu loop
  menuFlag = False # Declare and set the flag to False here

  menu = input("Choose the menu: ")
  # ...

  while True: # Choose character loop
    if menuFlag: break  # Do not forget to break all outer loops   

    character = input("Choose a character: ")
    # ...

    while True: # Any other loop (choose weapon, ...)
        weapon = input("Choose weapon: ")

        # Here you want to return to the menu if f is pressed
        # Set the flag to True in this condition
        if weapon == "f":
            menuFlag = True
            break

在您的游戏中,这类似于:

goToMainMenu = False

while True:
    if goToMainMenu: break
    vocationchoice = input("Select vocation.\nPress P for Royal Paladin: ")

    if vocationchoice == "P" or vocationchoice == "p":
        #ask user to input magic level for paladin
        num1 = float (input("Enter your magic level: "))

        #ask for own training dummy
        while True:
            if goToMainMenu: break

            trainingdummy = input("Do you have your own exercise dummy?\nType Y for yes and N for no: ")
            if trainingdummy == "y" or trainingdummy == "Y":
                #loop, where we ask user to input what exercise weapon they want to calculate
                while True:
                    while True:
                        weaponchoice = input("Select exercise weapon:\n1. Training rod: ")
                        if weaponchoice == "q":
                            sys.exit() #quit the program
                        if weaponchoice == "1" or weaponchoice == "2" or weaponchoice == "3" or weaponchoice == "f":
                            break #break out of the input loop

                    #User choice
                    if weaponchoice == "1":
                        print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")

            if trainingdummy == "n" or trainingdummy == "N":
                #list the different exercise weapon

                #loop where ask user to input what exercise weapon they want to calculate
                while True:
                    weaponchoice = input("Select exercise weapon (press F for main menu):\n1. Training rod: ")
                    #User choice
                    if weaponchoice == "1":
                        print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")

                    elif weaponchoice == "f" or weaponchoice == "F":
                        goToMainMenu = True
                        break

【讨论】:

  • 非常感谢!程序如何知道主菜单是什么?我应该把它命名为,或者?
  • 您应该在要进入的范围(循环)中声明标志(即布尔值),并且必须将其设置为False。我在答案中添加了一个示例。
  • 请注意,您可以声明所需的任意数量的标志。请注意,标志不容易维护,因为您很容易忘记编写 break 语句,而且它们往往会污染代码。
  • 我只是错过了第一个例子,现在我明白了。非常感谢您帮助我 Louis Lac!
  • 成功了。正如你所说,我注意到这给我带来了另一个问题,那就是维护和跟踪似乎有点费力。我想最初,最好不要像我处理这段代码那样陷入循环。
【解决方案2】:

This 我认为会帮助你。 Break 仅从当前循环中断。如果你想升级,你需要分别从每个循环中打破。

suggestion 是将循环转换为函数并使用 return 将有效地退出任何循环。不过需要进行一些代码重构。

如果不是这样,您能否提供更多信息和完整代码(我们在这里看不到更高的循环?)

【讨论】:

  • 问题是,如果我删除了最后一个 break 语句 (elif weaponchoice == f),它不会继续在那个循环中运行,不应该这样做吗?
  • @austiker 只是稍微更改了回复。希望现在对您有帮助
【解决方案3】:

weaponchoice == "1" 添加break 以退出循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2021-08-31
    • 2015-08-04
    • 1970-01-01
    • 2012-01-16
    • 2015-04-26
    • 1970-01-01
    相关资源
    最近更新 更多