0
votes

This is my fourth python script, so please bear with my newbieness... I am writing a script that tells the day of week on a certain date. It all runs fine except one error. I have a faint idea as to what is wrong, but am not too certain:

TypeError: 'int' object is not subscriptable

#!/usr/bin/python
import sys, string

# Call example:  day_of_week(2,10,1988); February 10, 1988
def day_of_week(month, date, year):
    # January
    if month == 1: m = 11
    # February
    elif month == 2: m = 12
    # March
    elif month == 3: m = 1
    # April
    elif month == 4: m = 2
    # May
    elif month == 5: m = 3
    # June
    elif month == 6: m = 4
    # July
    elif month == 7: m = 5
    # August
    elif month == 8: m = 6
    # September
    elif month == 9: m = 7
    # October
    elif month == 10: m = 8
    # November
    elif month == 11: m = 9
    # December
    elif month == 12: m = 10

    # Calculate the day of the week
    dow = (date + ((13 * m-1)/5) + year[2:] + (year[2:]/4) + (year[:2]/4) - 2 * year[:2]) % 7)

    # Formatting!
    if dow == 0: return "Sunday"
    elif dow == 1: return "Monday"
    elif dow == 2: return "Tuesday"
    elif dow == 3: return "Wednesday"
    elif dow == 4: return "Thursday"
    elif dow == 5: return "Friday"
    elif dow == 6: return "Saturday"
    else: return "Error!"

try:
    m = int(raw_input("What month were you born in (1-12)?  "))
    if not 1 <= m <= 12: raise Exception("There are no months with a number higher than 12!")
    d = int(raw_input("On what date were you born on?  "))
    y = int(raw_input("What year were you born in?  "))
    print("\nYou were born on a %s!" % day_of_week(m,d,y))
except ValueError:
    print("You need to enter a number!")
3
Do you need to use str() before slicing? - alex
Unrelated to the code, but python has a standard library module for calendar functionality calendar docs. - Wessie
You can use the following snippet to check your results: from datetime import date; d = date(2007, 9, 23); '{0:%A}'.format(d) # 'Sunday' - Jon Clements
@JonClements Ha, I need to start keeping track of all the cool code snippets you come up with :) - RocketDonkey
Tips: The elif chains are pretty laboured. In general could consider using dictionaries to map values instead. However the first one could be avoided by subtracting 2 and using modulo operator: m = (month - 2) % 12 - D Read

3 Answers

3
votes

In this line:

dow = (date + ((13 * m-1)/5) + year[2:] + (year[2:]/4) + (year[:2]/4) - 2 * year[:2]) % 7)

You are using year (an integer) and trying to return a slice from it. As the error indicates, int objects do not allow you to do this. In order to accomplish what you want, you would need to cast year as a string.

However an easier solution may be to use the built-in features of the datetime module to calculate the day of the week:

In [1]: import datetime

In [2]: my_date = datetime.date(2012, 11, 26)

In [3]: my_date.weekday()
Out[3]: 0

This uses Monday as the starting date (0). To keep with your current code, you can use isoweekday(), where Monday = 1:

In [11]: import datetime

In [12]: my_date = datetime.date(2012, 11, 26)

In [13]: my_date.isoweekday()
Out[13]: 1

You can then use @JonClement's slick snippet above to return the string of the day:

In [14]: '{0:%A}'.format(my_date)
Out[14]: 'Monday'
1
votes

You must cast your int to a string first, with str() in order to slice it.

1
votes

Don't cast your int to a string; use arithmetic:

century = year / 100
lasttwo = year % 100
dow = (date + ((13 * m-1)/5) + lasttwo + (lasttwo/4) + (century/4) - 2 * century) % 7)

And because I'm physically incapable of resisting such challenges, I tried to make the rest of the code a little more Pythonic:

#!/usr/bin/python

"""Calculate the day of the week of dates"""


def day_of_week(month, day, year):
    """Return the name of the weekday of the given date

    >>> day_of_week(1, 1, 1970)
    'Friday'
    >>> day_of_week(11, 26, 2012)
    'Monday'
    """
    moff = (month + 9) % 12 + 1

    # Calculate the day of the week
    century = year / 100
    lasttwo = year % 100
    dow = (day + (13 * moff - 1) / 5 + lasttwo + lasttwo / 4 + century / 4
        - 2 * century) % 7

    # Formatting!
    return ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
        "Saturday")[dow]


def main():
    """Test the program, then run it interactively"""
    import doctest
    testresult = doctest.testmod()
    if testresult.failed:
        import sys
        sys.exit(1)
    try:
        month = int(raw_input("What month were you born in (1-12)?  "))
        if not 1 <= month <= 12:
            raise Exception("Month must be between 1 and 12!")
        day = int(raw_input("On what date were you born on?  "))
        year = int(raw_input("What year were you born in?  "))
        print("\nYou were born on a %s!" % day_of_week(month, day, year))
    except ValueError:
        print("You need to enter a number!")

if __name__ == '__main__':
    main()

Notice that the actual logic is identical to your version. It just uses code that's a bit simpler. I presume that your end goal is more about learning Python than it is actually performing this calculation. If I'm wrong, scratch all of the above and use the datetime module which is far simpler still.