Search code examples
pythonfunctiondictionary

Using dictionary inside a function


I found an exercise in a Udemy's Python course which asks me to create a function called return_day. It suggests me to use a dictionary, but I have been trying for the past two hours without success. So I passed the exercise writing:

def return_day(x):
    if x == 1:
        return "Sunday"
    elif x==2:
        return "Monday"
    elif x==3:
        return "Tuesday"
    elif x==4:
        return "Wednesday"
    elif x==5:
        return "Thursday"
    elif x==6:
        return "Friday"
    elif x==7:
        return "Saturday"
    return None

...but it's completely different. Could someone help me? Why the code below does not work?

def return_day(x):
    if x > 0 and x<=7:
        return x=dict(1="Sunday",2="Monday",3="Tuesday",4="Wednesday",5="Thursday",6="Friday",7="Saturday")

    return None

Solution

  • You should specify which language you are using. From the function definition it seems Python, from the dictionary definition I don't know. A proper Python code will be as follow:

    d={1:"Sunday",2:"Monday",3:"Tuesday",4:"Wednesday",5:"Thursday",6:"Friday",7:"Saturday"}
    def return_day(x):
        return d[x]
    
    return_day(7) # return 'Saturday'