Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'function' object is not subscriptable - Python

Tags:

I've tried to solve an assignment with this code:

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: ")))

But when I run it, I get the error:

TypeError: 'function' object is not subscriptable

I don't understand where this is coming from...

like image 404
HorrorBoy Jay Avatar asked Mar 17 '15 14:03

HorrorBoy Jay


People also ask

How do I fix TypeError function object is not Subscriptable?

The error “TypeError: 'function' object is not subscriptable” occurs when you try to access an item from a function. Functions cannot be indexed using square brackets. To solve this error, ensure functions have different names to variables. Always call a function before attempting to access the functions.

What does it mean in Python when an object is not Subscriptable?

Python TypeError: 'int' object is not subscriptableThis error occurs when you try to use the integer type value as an array. In simple terms, this error occurs when your program has a variable that is treated as an array by your function, but actually, that variable is an integer.

How do I fix TypeError NoneType object is not Subscriptable in Python?

TypeError: 'NoneType' object is not subscriptable Solution The best way to resolve this issue is by not assigning the sort() method to any variable and leaving the numbers.

How do I fix TypeError float object is not Subscriptable in Python?

TypeError: 'float' object is not subscriptable. Solution: Do print("area of the circle :",area) instead of print("area of the circle :",area[0]) in line 10 of the code.


2 Answers

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

like image 60
unutbu Avatar answered Oct 07 '22 00:10

unutbu


It is so simple, you have 2 objects with the same name, and when you say: bank_holiday[month] Python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

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: ")))
like image 21
Peyman Majidi Avatar answered Oct 07 '22 00:10

Peyman Majidi