anishjp
anishjp

Reputation: 115

Python code using dictionary & function

I am trying to program a simple python code using dictionary & function as below

#Write a program to input number of week's day (1-7) and translate to its equivalent name of the day of the week.

options = { "1" : "sunday",
            "2" : "monday",
            "3" : "tuesday",
            "4" : "wednesday",
            "5" : "thursday",
            "6" : "friday",
            "7" : "saturday" }

options[raw_input("Enter number of weeks day (1-7):")]

def sunday():
    print "The day is Sunday"

def monday():
    print "The day is Monday"

def tuesday():
    print "The day is Tuesday"

def wednesday():
    print "The day is Wednesday"

def thursday():
    print "The day is Thursday"

def friday():
    print "The day is Friday"

def saturday():
    print "The day is Saturday"

The output is

[anishjp@localhost Python_programs]$ python hello24.py
Enter number of weeks day (1-7):1
[anishjp@localhost Python_programs]$

It doesn't print "The day is sunday". Can anyone tell me, what am I doing wrong here?

Upvotes: 1

Views: 184

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34176

The keys of the dictionary options are strings. You could store functions instead:

options = { "1" : sunday,
            "2" : monday,
            "3" : tuesday,
            "4" : wednesday,
            "5" : thursday,
            "6" : friday,
            "7" : saturday}

But, since you are making reference to those functions, they have to be declared before the dictionary definition:

def sunday():
    print "The day is Sunday"

...

def saturday():
    print "The day is Saturday"

options = { "1" : sunday,
            "2" : monday,
            "3" : tuesday,
            "4" : wednesday,
            "5" : thursday,
            "6" : friday,
            "7" : saturday}

Finally, to call it, you have to pass arguments. Your functions doesn't expect any arguments so the brackets will be empty ():

options[raw_input("Enter number of weeks day (1-7):")]()

Upvotes: 5

Chris Arena
Chris Arena

Reputation: 1630

The simple way to do this is to write a function that takes one parameter, the numbered day, and then uses your dictionary to print the day's name.

#Write a program to input number of week's day (1-7) and translate to its equivalent name of the day of the week.

options = {
    "1": "sunday",
    "2": "monday",
    "3": "tuesday",
    "4": "wednesday",
    "5": "thursday",
    "6": "friday",
    "7": "saturday"
}

def print_day(day_number):
    day_name = options[day_number]
    print("The day is {}".format(day_name))

input_number = input("Enter number of weeks day (1-7):")
print_day(input_number)

Obviously you can also add some error handling here for if the user gives an invalid number (less than 1, greater than 7, not an integer, etc.).

Upvotes: 2

Related Questions