M15671
M15671

Reputation: 57

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.

Upvotes: 0

Views: 187

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

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

Upvotes: 2

Rushy Panchal
Rushy Panchal

Reputation: 17532

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)

Upvotes: 2

mishik
mishik

Reputation: 10003

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

Upvotes: 3

Related Questions