为什么我的while循环在收到不同的指令后继续调用我的菜单函数?



我有一个简单的Python程序,它具有多个函数,显示菜单,接受输入,循环并格式化CSV文件,然后根据用户的输入从该CSV文件输出信息。

菜单选项看起来像

1: Call menu again
2: Create a default Report
3: More specified report
4: More specified Report
5: Exit program

我使用while循环来遍历这些菜单选项,这样我就可以在用户继续输入1时反复调用菜单。

来看看while循环

def main():
banner()
while True:
choice = menu()
#if the choice = 1, we call the menu function again 
if choice == 1:
menu()
elif choice == 2:
defaultReport()
break
elif choice == 3:
#elif statement for a function not yet created in part 1
pass
elif choice == 4:
#elif statement for a function not yet created in part 1
pass
elif choice ==5:
print('nExiting Program')
break

目标是能够在输入(choice) = 1时调用菜单函数,然后一旦输入等于其他值,程序就执行与输入对应的代码,而无需再次调用/显示菜单

进行。当前问题:

  1. 1 -再次调用/显示菜单第一次输入
  2. 1 -再次调用/显示菜单第二次输入
  3. 2 -应该显示一个默认报告,但是调用菜单/再次显示它
  4. 2-显示默认输出第4输入

目标:

  1. 1 -再次调用/显示菜单第一次输入
  2. 1 -再次调用/显示菜单第二次输入
  3. 2-显示默认输出第三输入

菜单功能:

def menu():
print('''nMortality Rate Comparison Menu

1. Show This Menu Again
2. Full Mortality Report by State
3. Mortality for a Single State, by Date Range
4. Mortality Summary for all States
5. Exit n ''')
choice = input('Make your selection from the menu: ')
while True:
try:
int(choice)
break
except:
choice = input('Make your selection from the menu: ')
while int(choice) > 5 or int(choice) < 1:
choice = input('Make your selection from the menu: ')
return int(choice)
while True:
...

是一个无限循环,它将一直运行,直到遇到break语句。

所有的break语句都在if/elif分支中,但并不是所有的分支都有break。不退出循环的逻辑原因要么是(i)没有一个if测试匹配,要么是(ii)没有一个带有break的分支匹配。

你可以改变你的程序来弄清楚发生了什么,例如,使用断言来验证值是合理的,并覆盖循环的所有出口,这样你就知道它要去哪里了:

def main():
banner()
while True:
choice = menu()
assert isinstance(choice, int), "choice is not an int"
assert 1 <= choice <= 5, "choice is not in [1..5]"
if choice == 1:
menu()
#... etc
elif choice == 5:
print('nExiting Program')
break
else:
print("Nothing matched..?  Choice is:", choice)
print("Debug...: end of while")

这可能是因为您没有重置选项的值。在循环开始时,您将其设置为menu(),然后每次继续这样做,我不确定menu()做什么,但我猜它每次都会返回1,这不是您想要的。

确保从调用menu()中接收到的值可能通过给它一些参数来改变,或者每次都要求输入,可能通过python shell。希望能有所帮助

最新更新