简体   繁体   中英

How to repeat input after input is typed?

I wrote a function that contains a dictionary of abbreviated week days to the full name of the day. I get the proper output day when I type in the abbreviation, but in order to try another abbreviation, I have to retype the function.

I have:

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

The problem I have is that it prints the full day name over and over again, and instead I want it to print the full day name, then print 'Enter day abbreviation' again.

It should look like this:

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

Instead, I get:

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

I know this is a really simple solution, but I can't figure it out.

You never reread "day" so "while day in days" is always true and executing endlessly.

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

You want to get input again in every iteration:

while True:
        day = input('Enter day abbreviation ' )
        acquired_day = days.get(day)
        if acquired_day is None: break
        print(acquired_day)
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

output:

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

Another way using 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 ' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM