bboychua
bboychua

Reputation: 41

Accessing a Dictionary Using Get

For this problem assume the following assignment statement has been executed.

weekdays = {'Sunday':0, 'Monday':1, 'Tuesday':2, 'Wednesday':3,
            'Thursday':4, 'Friday':5, 'Saturday':6}

Assume the variable day contains a value that may or may not be the name of a day. Write an assignment statement using get that assigns to day_num the day number if day contains the name of a day and -1 otherwise.

For example, if day is 'Wednesday' then day_num should be 3 and if day is 'Talk Like a Pirate Day' then day_num should be -1.

Here is my code:

day_num = weekdays.get(day)
if day_num==None:
   day_num=-1

I just don't understand why is it still wrong; it is correct I think. The homework system keeps on showing

You should use only one assignment statement (and nothing else)

Upvotes: 1

Views: 400

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

You are using two assignment statements. Perhaps you should give dict.get() a second argument:

day_num = weekdays.get(day, -1)

That second argument is a default to return if day is not present in the dictionary; the default default is None but here I return -1 instead.

This saves you a test for is None and a second assignment.

Upvotes: 1

Related Questions