Python多个用户输入 - 在退出之前浏览所有输入

时间:2014-10-24 13:15:00

标签: python-2.7 if-statement while-loop user-input exit

我正在尝试设置一个简单的用户输入菜单(非gui),如下所示:

如果用户输入0:

  1. 已加载文件。
  2. 菜单出现选项1-5提示 另一个用户输入从1到5.现在,在这里,在第一个用户之后 输入,一些处理完成。然后我想问问用户 用于第二个用户输入。这应该持续到用户输入为止 6岁或以上。
  3. 否则(如果用户未输入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退出。

    问题: 处理后,如何更改此代码以允许用户输入剩余的输出?

1 个答案:

答案 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()