0

这是我的第四个 python 脚本,所以请耐心等待我的新手......我正在编写一个脚本来告诉某个日期的星期几。除了一个错误,一切都运行良好。我对出了什么问题有一个模糊的想法,但不太确定:

TypeError:“int”对象不可下标

#!/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!")
4

3 回答 3

3

在这一行:

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

您正在使用year(一个整数)并试图从中返回一个切片。如错误所示,int对象不允许您这样做。为了完成您想要的,您需要转换year为字符串。

然而,更简单的解决方案可能是使用模块的内置功能datetime来计算星期几:

In [1]: import datetime

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

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

这使用星期一作为开始日期 (0)。为了与您当前的代码保持一致,您可以使用isoweekday(),其中 Monday = 1:

In [11]: import datetime

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

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

然后,您可以使用上面@JonClement 的简洁片段返回当天的字符串:

In [14]: '{0:%A}'.format(my_date)
Out[14]: 'Monday'
于 2012-11-27T00:20:58.150 回答
1

不要将您的 int 转换为字符串;使用算术:

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

而且因为我身体上无法抵抗这样的挑战,所以我试图让其余的代码更加 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()

请注意,实际逻辑与您的版本相同。它只是使用更简单的代码。我认为您的最终目标更多是关于学习 Python,而不是实际执行此计算。如果我错了,请从头开始以上所有内容并使用datetime更简单的模块。

于 2012-11-27T00:28:28.977 回答
1

您必须先将int其转换为string第一个,str()然后才能对其进行切片。

于 2012-11-27T00:21:26.137 回答