我编写了一个主脚本,该脚本具有一个包含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
答案 0 :(得分:0)
在您的代码中,当您调用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
答案 1 :(得分:0)
您有嵌套循环,break
仅跳出内部循环。
要解决此问题,请从break
块中删除嵌套循环和else
:
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")