簡體   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