TypeError:' int'对象在等式中不可订阅

时间:2012-11-27 00:16:39

标签: python typeerror

这是我的第四个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!")

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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模块。

答案 2 :(得分:0)

您必须首先使用str()int投射到string,以便对其进行切片。