键入输入后如何重复输入?

时间:2013-06-09 16:54:24

标签: python python-3.x

我写了一个函数,其中包含缩写的工作日字典到当天的全名。当我输入缩写时,我得到了正确的输出日,但为了尝试另一个缩写,我必须重新输入该函数。

我有:

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))

我遇到的问题是它一遍又一遍地打印全天名称,而我希望它打印全天名称,然后再次打印“输入日期缩写”。

它应该是这样的:

>>>weekday():
Enter day abbreviation: Tu
Tuesday
Enter day abbreviation: Su
Sunday
Enter day abbreviation:
...

相反,我得到:

>>>weekday():
Enter day abbreviation: Tu
Tuesday
Tuesday
Tuesday
Tuesday
Tuesday
... # it continues without stopping

我知道这是一个非常简单的解决方案,但我无法弄明白。

3 个答案:

答案 0 :(得分:3)

你永远不会重读“白昼”,所以“日复一日”总是如此,并且无休止地执行。

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)

您希望在每次迭代中再次获得输入:

while True:
        day = input('Enter day abbreviation ' )
        acquired_day = days.get(day)
        if acquired_day is None: break
        print(acquired_day)

答案 2 :(得分:2)

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

<强>输出:

$ python3 so.py
Enter day abbreviation Mo
Monday
Enter day abbreviation Tu
Tuesday
Enter day abbreviation we
Wednesday
Enter day abbreviation foo

使用dict.get的另一种方式:

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 ' )