TypeError:'function'对象不可订阅 - Python

时间:2015-03-17 14:32:24

标签: python

我尝试使用此代码解决作业:

bank_holiday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bank_holiday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

但是当我运行它时,我收到错误:

TypeError: 'function' object is not subscriptable

我不明白这是来自哪里......

3 个答案:

答案 0 :(得分:12)

您有两个名为bank_holiday的对象 - 一个是列表,另一个是函数。消除两者的歧义。

bank_holiday[month]引发错误,因为Python认为bank_holiday引用了函数(绑定到名称bank_holiday的最后一个对象),而您可能打算将其表示为列表。< / p>

答案 1 :(得分:1)

这是如此简单,您有两个名称相同的对象,当您说:bank_holiday [month] python认为您想运行函数并出现错误。

只需将数组重命名为bank_holidays <---在末尾添加一个“ s”!像这样:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ?")

bank_holiday(int(input("Which month would you like to check out: ")))

答案 2 :(得分:0)

您可以使用此:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))