我目前正在完成一个生成人口模型的程序。 程序需要重复,所以当完成一个选项时,它必须返回菜单。
我尝试过各种解决方案来解决这个问题,比如为菜单创建一个函数(但是函数会限制你创建全局变量)
我也试过创建一个看起来像这样的while循环:
import csv
import time
time.sleep(1)
menu = True
while menu:
print ("1. Set the Generation 0 values")
print ("2. Display the Generation 0 values")
print ("3. Run the model")
print ("4. Export data")
print ("5. Exit")
但它出现了:
1. Set the Generation 0 values
2. Display the Generation 0 values
3. Run the model
4. Export data
5. Exit
1. Set the Generation 0 values
2. Display the Generation 0 values
3. Run the model
4. Export data
5. Exit
它重复出现!
所以主要的问题是如何重复菜单,我知道使用while循环有帮助,但是如何阻止它重复?
答案 0 :(得分:0)
您需要在循环中将menu
设置为False
。否则 - 它是一个无限循环,所以当然它只是不断重复菜单。
类似的东西:
while menu:
print ("1. Set the Generation 0 values")
print ("2. Display the Generation 0 values")
print ("3. Run the model")
print ("4. Export data")
print ("5. Exit")
choice = input("Please select your choice (1-5)")
if choice == '1':
pass #replace by code for choice 1
elif choice == '2':
pass #replace by code for choice 2
elif choice == '3':
pass #replace by code for choice 3
elif choice == '4':
pass #replace by code for choice 4
else:
menu = False #anything other than 1-4 breaks out of loop
在评论中,我说的是“替换为选择代码3”。如果有问题的代码超过1或2行,则应将其抽象为函数,以便在上面的代码中可以对各种情况进行简单的函数调用。