如何循环答案,以便如果用户输入1,2或3并执行该功能,它会再次询问他们的选择?

时间:2014-07-21 16:02:19

标签: python python-3.3

  1. 允许用户提交配对
  2. 允许用户删除配对
  3. 允许用户提交最终配对
  4. 如何编辑程序以便用户(在完成1,2或3之后)再次询问相同的问题? (问题= user_selection)

    clue_list = {'#':'A', '%':'N', '*':'M'}
    
    user_selection = input('What would you like to do? 1.Submit a letter or symbol pairing,     2.Delete a letter/symbol pairing, 3. Submit Final Answers ')
    while user_selection != '3':
    if user_selection == '1':
        userkey = input('Please enter a symbol to add: ')
        uservalue = input('Please enter a letter to add: ')
        if userkey in clue_list:
            print('This symbol has already been matched. Please try again.')
        else:
            clue_list[userkey] = uservalue
        print(clue_list)
    if user_selection == '2':
        user_delete_input = input('What letter/symbol would you like to delete? (Please enter symbol to delete the pairing ')
        if user_delete_input in clue_list:
            del clue_list[user_delete_input]
            print('That letter/symbol has been deleted.')
        else:
            print('Error: That letter/symbol has not been found in file.')                
    
    user_submit1 = input('Would you like to submit more pairings? Yes/No ')
    if user_submit1 == 'Yes':
        function_result2 = submit(clue_list)
    else:
        if user_submit1 == 'No':
           print('...')
    

1 个答案:

答案 0 :(得分:0)

问题的关键在于重复选择过程。如果您学习使用函数抽象出部分代码,则可以非常轻松地完成此操作。例如,您的问题的可能答案如下:

while True:
    user_selection = input(msg_ask).strip()
    if   user_selection == '1': add_symbol(clue_list)
    elif user_selection == '2': remove_symbol(clue_list)
    elif user_selection == '3': break

我们已经定义了add_symbolremove_symbol这样的函数:

clue_list = {'#':'A', '%':'N', '*':'M'}

msg_ask = '''
What would you like to do?
1. Submit a letter or symbol pairing,
2. Delete a letter/symbol pairing,
3. Submit Final Answers
'''

def add_symbol(clue_list):
    userkey = input('Please enter a symbol to add: ')
    uservalue = input('Please enter a letter to add: ')
    if userkey in clue_list:
        print('This symbol has already been matched.')
    else:
        clue_list[userkey] = uservalue
        print(clue_list)

def remove_symbol(clue_list):
    msg = 'What letter/symbol would you like to delete? (Please enter symbol to delete the pairing) '
    user_delete_input = input(msg)
    if user_delete_input in clue_list:
        del clue_list[user_delete_input]
        print('That letter/symbol has been deleted.')
    else:
        print('Error: That letter/symbol has not been found in file.')               

您会注意到第一个代码块 更容易阅读。