-2

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

Community
  • 1
  • 1

2 Answers2

3

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

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

Haroon
  • 480
  • 4
  • 14
  • it works but not very pythonic... – Fredrik Pihl Feb 24 '14 at 17:53
  • 1
    Ya you are right but i think the guy need simple solution so that he can understand.. that why i wrote this.. – Haroon Feb 24 '14 at 17:55
  • fair enough, you get a +1 :-) – Fredrik Pihl Feb 24 '14 at 17:58
  • The simpler solution is to use a dictionary; map a key to a string. The simplest solution is to use a list, since the keys here are contiguous positive integers starting at 0. – Martijn Pieters Feb 24 '14 at 18:00
  • Thanks but it says there is a syntax error in first line? – Marco Lourenco Feb 24 '14 at 18:01
  • Hi Marco, Sorry i miss : after dayOfTheWeek(n) now try the code.. Thanks – Haroon Feb 24 '14 at 18:09
  • Marco go to the site.. http://repl.it/languages/Python And run the code.. 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" print dayOfTheWeek(4) – Haroon Feb 24 '14 at 18:13