繁体   English   中英

虽然循环没有中断?

[英]While loop not breaking?

我编写了一个主脚本,它有一个包含 5 个不同选项的菜单,第五个选项是用户是否想退出程序。 如果用户在主菜单中键入 5,程序应该退出,但它没有......它只是继续循环浏览菜单。 谁能帮我解决这个问题??

menuItems = np.array(["Load new data", "Check for data errors", "Generate plots", "Display list of grades","Quit"])

userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)


while True:

    choice = displayMenu(menuItems)

    while True:
        if (choice == 1):
            userinput = input("Please enter name of the data file: ")
            grades = dataLoad(userinput)
            break


        elif (choice == 2):
            checkErrors(grades)
            break

        elif choice == 3:
            gradesPlot(grades)

        elif choice == 4:
            show = listOfgrades(grades)
            showList(show)

        elif (choice == 5):
            break


        else:
            print("Invalid input, please try again")
            break

在您的代码中,当您调用 break 时,它会从内部 while 循环中断并转到外部 while 循环,这会导致整个过程再次进行。 如果在某些情况下您希望两个 while 循环都中断,那么您可以使用某种标志。

例子,

flag = False

while True:
    while True:
        if (1 == var):
            flag = True
            break
    if flag:
        break

//你的代码

flag = False
while True:

    choice = displayMenu(menuItems)

    while True:
        if (choice == 1):
            userinput = input("Please enter name of the data file: ")
            grades = dataLoad(userinput)
            flag = True
            break


        elif (choice == 2):
            checkErrors(grades)
            flag = True
            break

        elif choice == 3:
            gradesPlot(grades)

        elif choice == 4:
            show = listOfgrades(grades)
            showList(show)

        elif (choice == 5):
            flag = True
            break


        else:
            print("Invalid input, please try again")
            flag = True
            break

    if True == flag:
        break

您有嵌套循环,并且break只中断内部循环。

要解决此问题,请从else块中删除嵌套循环和break

while True:
    choice = displayMenu(menuItems)

    if (choice == 1):
        userinput = input("Please enter name of the data file: ")
        grades = dataLoad(userinput)
        break
    elif (choice == 2):
        checkErrors(grades)
        break
    elif choice == 3:
        gradesPlot(grades)
    elif choice == 4:
        show = listOfgrades(grades)
        showList(show)
    elif (choice == 5):
        break
    else:
        print("Invalid input, please try again")

暂无
暂无

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

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