我正在尝试设置一个简单的用户输入菜单(非gui),如下所示:
如果用户输入0:
否则(如果用户未输入0) 打印"错误退出。请重启程序。"
这就是我所拥有的:
import csv
# Load input file:
choiceloading = input('Please enter 0 to load the input file: ')
if choiceloading == 0:
with open('eggs.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print ', '.join(row)
print (" M A I N - M E N U")
print ("1. Action 1")
print ("2. Action 2")
print ("3. Action 3")
print ("4. Action 4")
print ("5. Action 5")
# Get user input:
choice = raw_input('Enter choice [1-5] : ')
# Convert input (number) to int type:
choice = int(choice)
# Perform action based on menu-option selection by user:
if choice == 1:
print ("Action 1...")
#processing #1 is done here
elif choice == 2:
print ("Action 2...")
#processing #2 is done here
elif choice == 3:
print ("Action 3...")
#processing #3 is done here
elif choice == 4:
print ("Action 4...")
#processing #4 is done here
elif choice == 5:
print ("Action 5...")
#processing #5 is done here
else:
print ("Invalid entry. You should choose 1-5 only. Program exiting.....please restart it and try again.")
else:
print ("Invalid entry. You should choose 0 to load the file. Program exiting.....please restart it and try again.")
目前,该程序只接受1个用户输入。处理完毕后,退出。恩。如果用户输入3,并且3的处理完成,则程序将退出。
但是,我想允许用户输入1,2,4,5来处理1,2,4,5。然后他们应该输入> 5退出。
问题: 处理后,如何更改此代码以允许用户输入剩余的输出?
答案 0 :(得分:1)
最简单的方法是在循环中添加处理,如下所示:
while True:
# Get user input:
choice = raw_input('Enter choice [1-5] : ')
# Convert input (number) to int type:
choice = int(choice)
if choice == 1:
print ("Action 1...")
#processing #1 is done here
elif choice == 2:
print ("Action 2...")
#processing #2 is done here
elif choice == 3:
print ("Action 3...")
#processing #3 is done here
elif choice == 4:
print ("Action 4...")
#processing #4 is done here
elif choice == 5:
print ("Action 5...")
#processing #5 is done here
else:
print ("Invalid entry. You should choose 1-5 only. Program exiting.....please restart it and try again.")
# Add sys.exit() (will have to add 'import sys' to top
else:
print ("Invalid entry. You should choose 0 to load the file. Program exiting.....please restart it and try again.")
# Add sys.exit()