Question

A question I can't work out, is how to write a function day_name that converts an integer 0-6 into Sunday to Monday, 0 being Sunday.

I found this helpful but the year and month confuse me = which day of week given a date python

Était-ce utile?

La solution

All you need is a list of weekdays:

weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

then use the day integer as an index:

def day_name(day):
    return weekdays[day]

This works because Python lists use 0-based indexing:

>>> weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
>>> weekdays[0]
'Sunday'
>>> weekdays[5]
'Friday'

Autres conseils

Hi here is your function

def dayOfTheWeek(n):
    if n == 0:
       return "Sunday"
    elif n == 1:
       return "Monday"
    elif n == 2:
       return "Tuesday"
    elif n == 3:
       return "Wednesday"
    elif n == 4:
       return "Thursday"
    elif n == 5:
       return "Friday"
    elif n == 6:
       return "Saturday"
    else:
       return "Invalid Number"

I hope thats what you are looking for :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top