Typeerror int object is not callable ошибка

Given the following:

a = 23
b = 45
c = 16

round((a/b)*0.9*c)

Running the above outputs an error:

TypeError: 'int' object is not callable.

How can I round the output to an integer?

Mateen Ulhaq's user avatar

Mateen Ulhaq

24.7k19 gold badges102 silver badges135 bronze badges

asked Mar 19, 2012 at 9:05

rob's user avatar

3

Somewhere else in your code you have something that looks like this:

round = 42

Then when you write

round((a/b)*0.9*c)

that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.

The problem is whatever code binds an int to the name round. Find that and remove it.

answered Mar 19, 2012 at 9:08

David Heffernan's user avatar

David HeffernanDavid Heffernan

602k42 gold badges1076 silver badges1491 bronze badges

2

I got the same error (TypeError: ‘int’ object is not callable)

def xlim(i,k,s1,s2):
   x=i/(2*k)
   xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
   return xl 
... ... ... ... 

>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable

after reading this post I realized that I forgot a multiplication sign * so

def xlim(i,k,s1,s2):
   x=i/(2*k)
   xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
   return xl 

xlim(1.0,100.0,0.0,0.0)
0.005

tanks

Duncan Leung's user avatar

answered Jul 17, 2015 at 18:45

Tomate's user avatar

TomateTomate

1951 silver badge5 bronze badges

3

Stop stomping on round somewhere else by binding an int to it.

answered Mar 19, 2012 at 9:07

Ignacio Vazquez-Abrams's user avatar

0

I was also facing this issue but in a little different scenario.

Scenario:

param = 1

def param():
    .....
def func():
    if param:
        var = {passing a dict here}
        param(var)

It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.

Changed function name to something else and it worked.

So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.

I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.

bad_coder's user avatar

bad_coder

11.3k20 gold badges44 silver badges72 bronze badges

answered Mar 4, 2020 at 12:04

Sugandha Jain's user avatar

0

In my case I changed:

return <variable>

with:

return str(<variable>)

try with the following and it must work:

str(round((a/b)*0.9*c))

eyllanesc's user avatar

eyllanesc

236k19 gold badges170 silver badges242 bronze badges

answered Apr 11, 2018 at 17:40

Jonathan Arias's user avatar

Sometimes the problem would be forgetting an operator while calculation.

Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))

HTH

answered Jun 12, 2021 at 19:16

Mebatsion Sahle's user avatar

There are two reasons for this error «TypeError: ‘int’ object is not callable«

  1. Function Has an Integer Value

Consider

a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)

This will produce TypeError: ‘int’ object is not callable.

Just change the variable name «max» to var(say).

a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)

The above code will run perfectly without any error!!

  1. Missing a Mathematical Operator

Consider

a = 5
b = a(a+1)
print(b)

This will also produce TypeError: ‘int’ object is not callable.

You might have forgotten to put the operator in between ( ‘*’ in this case )

answered Jul 21, 2021 at 9:47

Shambhav Agrawal's user avatar

1

As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.

answered Apr 10, 2020 at 13:20

krishnakeshan's user avatar

krishnakeshankrishnakeshan

1,2422 gold badges14 silver badges18 bronze badges

You can always use the below method to disambiguate the function.

__import__('__builtin__').round((a/b)*0.9*c)

__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.

answered Sep 12, 2021 at 14:59

Nithish Thomas's user avatar

I encountered this error because I was calling a function inside my model that used the @property decorator.

@property
def volume_range(self):
    return self.max_oz - self.min_oz

When I tried to call this method in my serializer, I hit the error «TypeError: ‘int’ object is not callable».

    def get_oz_range(self, obj):
      return obj.volume_range()

In short, the issue was that the @property decorator turns a function into a getter. You can read more about property() in this SO response.

The solution for me was to access volume_range like a variable and not call it as a function:

    def get_oz_range(self, obj):
      return obj.volume_range # No more parenthesis

answered Jun 25, 2022 at 20:54

Code on the Rocks's user avatar

FYI: the 'int' object is not callable error also appears if you accidentally use .size() as a method (which does not exist) instead of the .size property in Pandas dataframes as demonstrated below. Thus the error can appear in unexpected places.

import pandas as pd
s = pd.Series([35, 52, 63, 52])
print("unique numbers: ",s.unique())
print("number of unique values: ",s.unique().size())

answered May 15 at 14:09

w. Patrick Gale's user avatar

Typeerror: int object is not callable – How to Fix in Python

In Python, a “Typeerror” occurs when you use different data types in an operation.

For example, if you attempt to divide an integer (number) by a string, it leads to a typeerror because an integer data type is not the same as a string.

One of those type errors is the “int object is not callable” error.

The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int(), sum(), max(), and others.

The error also occurs when you don’t specify an arithmetic operator while performing a mathematical operation.

In this article, I will show you how the error occurs and what you can do to fix it.

How to Fix Typeerror: int object is not callable in Built-in Function Names

If you use a built-in function name as a variable and call it as a function, you’ll get the “int object is not callable” error.

For instance, the code below attempts to calculate the total ages of some kids with the built-in sum() function of Python. The code resulted in an error because the same sum has already been used as a variable name:

kid_ages = [2, 7, 5, 6, 3]

sum = 0
sum = sum(kid_ages)
print(sum)

Another example below shows how I tried to get the oldest within those kids with the max() function, but I had declared a max variable already:

kid_ages = [2, 7, 5, 6, 3]

max = 0
max = max(kid_ages)
print(max)

Both code examples led to this error in the terminal:
error

To fix the issue, you need to change the name of the variable you named as a built-in function so the code can run successfully:

kid_ages = [2, 7, 5, 6, 3]

sum_of_ages = 0
sum = sum(kid_ages)
print(sum)

# Output: 23
kid_ages = [2, 7, 5, 6, 3]

max_of_ages = 0
max = max(kid_ages)
print(max)

# Output: 7

If you get rid of the custom variables, your code will still run as expected:

kid_ages = [2, 7, 5, 6, 3]

sum = sum(kid_ages)
print(sum)

# Output: 23
kid_ages = [2, 7, 5, 6, 3]

max = max(kid_ages)
print(max)

# Output: 7

How to Fix Typeerror: int object is not callable in Mathematical Calculations

In Mathematics, if you do something like 4(2+3), you’ll get the right answer which is 20. But in Python, this would lead to the Typeerror: int object is not callable error.
ss2-2

To fix this error, you need to let Python know you want to multiply the number outside the parentheses with the sum of the numbers inside the parentheses.

To do this, you do this by specifying a multiplication sign (*) before the opening parenthesis:

print(4*(2+3))

#Output: 20

Python allows you to specify any arithmetic sign before the opening parenthesis.

So, you can perform other calculations there too:

print(4+(2+3))

# Output: 9
print(4-(2+3))

# Output: -1
print(4/(2+3))

# Output: 0.8

Final Thoughts

The Typeerror: int object is not callable is a beginner error in Python you can avoid in a straightforward way.

As shown in this article, you can avoid the error by not using a built-in function name as a variable identifier and specifying arithmetic signs where necessary.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Пытался написать сортировку списка с использованием рекурсии, начала вылезать ошибка TypeError: 'int' object is not callable после добавления рекурсии функции(до этого для тестов использовал списки из трех элементов — рекурсия была не нужна).

def a(mas):
    menshe = []
    bolshe = []
    sorted = []
    if len(mas) <= 2:
        return mas
    else:
        a = int(len(mas) // 2)
        vibor = mas[a]
        del mas[a]
        if len(mas) == 2:
            for i in mas:
                if i < vibor:
                    menshe.append(i)
                else:
                    bolshe.append(i)
            sorted.append(menshe)
            sorted.append(vibor)
            sorted.append(bolshe)
            print(sorted)
        else:
            a(mas)

Сорри за говно код, только учусь)

Dmytro Hoi's user avatar

задан 28 мар 2020 в 13:19

G3L10s's user avatar

6

Функция названа также, как и внутренняя переменная.

Таким образом, когда в последней строке вы «вызываете» a(mas) для программы в этот момент a уже переназначено и там число (из строки a = int(len(mas) // 2)).

Для того чтобы такие ошибки не возникали, пожалуйста прочитайте соглашения по форматированию кода и не используйте короткие a, b, i, j, k и прочие названия, а используйте осмысленные имена переменных и функций. Для функций обычно используют глагол или описание действия.

ответ дан 28 мар 2020 в 21:51

Dmytro Hoi's user avatar

In this article, we will be discussing the TypeError: “int” Object is not callable exception. We will also be through solutions to this problem with example programs.

Why Is This Error Raised?

  1. “int” is used as a variable name.
  2. Arithmetic Operator not provided when calculating integers.
  3. Placing parentheses after a number

Using int As A Variable, Name

Variable declaration using in-built names or functions is a common mistake in rookie developers. An in-built name is a term with its value pre-defined by the language itself. That term can either be a method or an object of a class.

int is an in-built Python keyword. As we discussed, it is not advisable to use pre-defined names as variable names. Although using a predefined name will not throw any exception, the function under the name will no longer be re-usable.

Let’s refer to the following example:

myNums = [56,13,21,54]
sum = 0
sum = sum(myNums)
print("sum of myNums list: ", sum)

Output and Explanation

TypeError: "int" Object Is Not Callable

  1. Variable myNums is a list of 4 integers.
  2. A variable sum is initialized with the value 0
  3. The sum of myNums list is calculated using sum() function and stored in sum variable.
  4. Results printed.

What went wrong here? In step 2, we initialize a variable sum with a value of 0. In Python, sum is a pre-defined function. When were try to use the sum function in step 3, it fails. Python only remembers sum as a variable since step 2. Therefore, sum() has lost all functionality after being declared as a variable.

Solution

Instead of using sum as a variable declaration, we can use more descriptive variable names that are not pre-defined (mySummySum, totalSum). Make sure to follow PEP 8 naming conventions.

myNums = [56,13,21,54]
totalSum = 0
totalSum= sum(myNums)
print("sum of myNums list: ", totalSum)

Correct Output

sum of myNums list:  144

Arithmetic Operator Not Provided When Calculating Integers

Failing to provide an arithmetic operator in an equation can lead to TypeError: “int” object is not callable. Let’s look at the following example:

prices = [44,54,24,67]
tax = 10
totalPrice = sum(prices)
taxAmount = totalPrice(tax/100)
print("total taxable amounr: ", taxAmount)

Output / Explanation

Arithmetic Operator Not Provided When Calculating Integers

  1. List of integers stored in the variable prices
  2. Tax percentage set to 10
  3. Total price calculated and stored in totalPrice
  4. Total Taxable amount calculated.
  5. Final result printed.

To calculate the taxable amount, we must multiply totalPrice with tax percentage. In step 4, while calculating taxAmount, the * operator is missing. Therefore, this gives rise to TypeError: "int" Object Is Not Callable

Solution

Denote all operators clearly.

prices = [44,54,24,67]
tax = 10
totalPrice = sum(prices)
taxAmount = totalPrice*(tax/100)
print("total taxable amounr: ", taxAmount)
total taxable amount:  18.900000000000002

Recommended Reading | [Solved] TypeError: ‘str’ object is not callable

Placing Parentheses After an Integer

Let’s look at the following code:

Output / Explanation

Placing Parentheses After an Integer

It is syntactically wrong to place parentheses following an integer. Similar to the previous section, It is vital that you ensure the correct operators.

Solution

Do not use brackets after a raw integer. Denote correct operators.

cursor.rowcount() TypeError: “int” Object Is Not Callable

Let’s look at the following code:

sample ="select * from myTable"
...
...
...
....
self.cur = self.con.cursor()
self.cur.execute(sample)              
print(self.cur.rowcount())

Error Output

TypeError: 'int' object is not callable

Solution

According to the sqlite3 documentation provided by Python, .rowcount is an attribute and not a function. Thereby remove the parenthesis after .rowcount.

sample ="select * from myTable"
...
...
...
....
self.cur = self.con.cursor()
self.cur.execute(sample)              
print(self.cur.rowcount)

Let’s refer to the following code.

contours,hierarchy = cv2.findContours(
thresh,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE
)

...
...
...
...

if (hierarchy.size() > 0):
    numObj =hierarchy.size()

Error Output

   if (hierarchy.size() > 0):
TypeError: 'int' object is not callable

Solution

The  hierarchy object returned is a numpy.ndarray object. You should also note that the numpy.ndarray.size attribute is an integer, not a method. Therefore, they cause the exception.

if event.type == pygame.quit() TypeError: ‘int’ Object Is Not Callable

Let’s refer to the example code to move an image:

import pygame
import sys 

pygame.init()
...
...
...

while True:
    for i in pygame.event.get():
       if i.type() == pygame.QUIT:
            sys.exit()
    ...
    ...

Error Output

if i.type() == pygame.QUIT:
TypeError: 'int' object is not callable

Solution

The condition statement should be:

if i.type == pygame.QUIT:

Instead of the current:

if i.type() == pygame.QUIT:

Please note that type is a member of the class Event, not a function. Therefore, it is not required to pass parenthesis.

TypeError: ‘int’ Object Is Not Callable Datetime

Let’s refer to the following code:

from datetime import *
...
...
...

for single_date in daterange(start_date, end_date):
    if single_date.day() == 1 and single_date.weekday() == 6: 
        sundays_on_1st += 1 

Error Output

TypeError: 'int' object is not callable

Solution

.day is not a function but an attribute. Therefore passing parenthesis should be avoided.

from datetime import *
...
...
...

for single_date in daterange(start_date, end_date):
    if single_date.day == 1 and single_date.weekday() == 6: 
        sundays_on_1st += 1 

[Fixed] io.unsupportedoperation: not Writable in Python

FAQs

How do I fix TypeError int object is not callable?

You can fix this error by not using “int” as your variable name. This will avoid the cases where you want to convert the data type to an integer by using int().

What does TypeError int object is not callable mean?

Object not callable simply means there is no method defined to make it callable. Usually, parenthesis is used to call a function or object, or method.

Conclusion

We have looked at the exception TypeError: ‘int’ Object Is Not Callable. This error mostly occurs due to basic flaws in the code written. Various instances where this error appears have also been reviewed.

Other Errors You Might Get

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

Error TypeError: ‘int’ object is not callable

This is a common coding error that occurs when you declare a variable with the same name as inbuilt int() function used in the code. Python compiler gets confused between variable ‘int’ and function int() because of their similar names and therefore throws typeerror: ‘int’ object is not callable error.

To overcome this problem, you must use unique names for custom functions and variables.

Example

##Error Code

#Declaring and Initializing a variable
int = 5;
#Taking input from user {Start}
productPrice = int(input("Enter the product price : "))
productQuantity = int(input("Enter the number of products : "))
#Taking input from user {Ends}

# variable to hold the value of effect on the balance sheet
# after purchasing this product.
costOnBalanceSheet = productPrice * productQuantity
#printing the output
print(costOnBalanceSheet) 

Output

Enter the product price : 2300
Traceback (most recent call last):
  File "C:\Users\Webartsol\AppData\Local\Programs\Python\Python37-32\intObjectnotCallable.py", line 3, in <module>
    productPrice = int(input("Enter the product price : "))
TypeError: 'int' object is not callable

In the example above we have declared a variable named `int` and later in the program, we have also used the Python inbuilt function int() to convert the user input into int values.

Python compiler takes “int” as a variable, not as a function due to which error “TypeError: ‘int’ object is not callable” occurs.

How to resolve typeerror: ‘int’ object is not callable

To resolve this error, you need to change the name of the variable whose name is similar to the in-built function int() used in the code.

#Code without error

#Declaring and Initializing a variable
productType = 5;
#Taking input from user {Start}
productPrice = int(input("Enter the product price : "))
productQuantity = int(input("Enter the number of products : "))
#Taking input from user {Ends}

# variable to hold the value of effect on the balance sheet
# after purchasing this product
costOnBalanceSheet = productPrice * productQuantity
#printing the output
print(costOnBalanceSheet)

OUTPUT:

Enter the product price : 3500
Enter the number of products : 23
80500 

In the above example, we have just changed the name of variable “int” to “productType”.

How to avoid this error?

To avoid this error always keep the following points in your mind while coding:

  • Use unique and descriptive variable names
  • Do not use variable name same as python in-built function name, module name & constants
  • Make the function names descriptive and use docstring to describe the function

Понравилась статья? Поделить с друзьями:
  • Typeerror failed to fetch ошибка
  • Type object has no attribute objects ошибка
  • Type myisam ошибка
  • Type mismatch vba word ошибка
  • Type module js ошибка