如何编辑程序以便用户(在完成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('...')
答案 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_symbol
和remove_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.')
您会注意到第一个代码块 更容易阅读。