How to repeat input after input is typed?
我写了一个函数,其中包含缩写的工作日字典到当天的全名。 当我输入缩写时,我得到了正确的输出日,但为了尝试另一个缩写,我必须重新输入该函数。
我有:
1 2 3 4 5 6 7 | def weekday() day = input('Enter day abbreviation ' ) days = {'Mo':'Monday','Tu':'Tuesday', 'we':'Wednesday', 'Th':'Thursday', 'Fr':'Friday', 'Sa':'Saturday','Su':Sunday'} while day in days: print(days.get(day)) |
我遇到的问题是它一遍又一遍地打印全天名称,而我希望它打印全天名称,然后再次打印"输入日期缩写"。
它应该如下所示:
1 2 3 4 5 6 7 | >>>weekday(): Enter day abbreviation: Tu Tuesday Enter day abbreviation: Su Sunday Enter day abbreviation: ... |
相反,我得到:
1 2 3 4 5 6 7 8 | >>>weekday(): Enter day abbreviation: Tu Tuesday Tuesday Tuesday Tuesday Tuesday ... # it continues without stopping |
我知道这是一个非常简单的解决方案,但我无法弄清楚。
你永远不会重读"日子",所以"日复一日"总是如此,并且无休止地执行。
1 2 3 4 5 6 7 8 | def weekday() day = input('Enter day abbreviation ' ) days = {'Mo':'Monday','Tu':'Tuesday', 'we':'Wednesday', 'Th':'Thursday', 'Fr':'Friday', 'Sa':'Saturday','Su':'Sunday'} while day in days: print(days.get(day)) day = input('Enter day abbreviation ' ) |
1 2 3 4 5 6 7 8 9 | days = {'Mo':'Monday','Tu':'Tuesday', 'we':'Wednesday', 'Th':'Thursday', 'Fr':'Friday', 'Sa':'Saturday','Su':'Sunday'} while True: day = input('Enter day abbreviation ' ) if day in days: print (days[day]) else: break |
输出:
1 2 3 4 5 6 7 8 | $ python3 so.py Enter day abbreviation Mo Monday Enter day abbreviation Tu Tuesday Enter day abbreviation we Wednesday Enter day abbreviation foo |
使用
1 2 3 4 5 6 7 8 | days = {'Mo':'Monday','Tu':'Tuesday', 'we':'Wednesday', 'Th':'Thursday', 'Fr':'Friday', 'Sa':'Saturday','Su':'Sunday'} obj = object() #returns a unique object day = input('Enter day abbreviation ' ) while days.get(day,obj) != obj: print (days[day]) day = input('Enter day abbreviation ' ) |
您希望在每次迭代中再次获得输入:
1 2 3 4 5 | while True: day = input('Enter day abbreviation ' ) acquired_day = days.get(day) if acquired_day is None: break print(acquired_day) |