首页 > 解决方案 > 为什么我们不能在 Python 中下标“int”对象

问题描述

我试图根据给定的年份返回月份中的天数,最后,如果年份不是闰年,它应该根据定义的列表返回天数,但我收到错误。

这是我的代码

days_of_month=[0,31,28,31,30,31,30,31,31,30,31,30,31]
year=int(input('enter the year - '))
month=int(input('enter the month - '))

def isleap(year):
    return year%4==0 and (year % 100!=0 or year % 400==0)
def days(month,year):
    if month > 12 or month < 1:
        print('Invalid')     
    else:
        if month==2 and isleap(year):
            return 29
        else:
            return month[days_of_month]    

print(days(month,year))            

错误信息

Traceback (most recent call last):
  File "d:\Function_Example.py", line 16, in <module>
    print(days(month,year))
  File "d:\Function_Example.py", line 14, in days
    return month[days_of_month]
TypeError: 'int' object is not subscriptable

有没有其他方法可以从列表中获取元素?

标签: pythonint

解决方案


你混淆了函数的最后一行。

它应该是:

days_of_month=[0,31,28,31,30,31,30,31,31,30,31,30,31]
year=int(input('enter the year - '))
month=int(input('enter the month - '))

def isleap(year):
    return year%4==0 and (year % 100!=0 or year % 400==0)
def days(month,year):
    if month > 12 or month < 1:
        print('Invalid')     
    else:
        if month==2 and isleap(year):
            return 29
        else:
            return days_of_month[month]    

print(days(month,year))  

推荐阅读