0

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.

1

3 Answers 3

3

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 ' )
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I don't know why I didn't think of that. So simple
2

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)

Comments

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

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

1 Comment

he expect to quit if day is not in days, as the wrong while loop condition states...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.