Getting the error in python when i am executing max(2,3)
>>> max(2,3)
Traceback (most recent call last):
file "<console>", line 1, in ?
TypeError: 'float' object is not callable
Is there any syntax problem ?
asked Dec 10, 2014 at 9:52
3
The code looks ok. You probably assigned some value to max
before it.
>>> max(2, 3)
3
>>> max = 3.4
>>> max(2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable
If you did not explicitly assign anything to max
, the problem may be in a file you imported.
answered Dec 10, 2014 at 9:54
Somewhere in your code you have put
max = some number
and now you are trying to use the max
function after having bound the name max
to a float
. This is why you should always be careful of variable names
>>> max = 9.0
>>> max(2, 3)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
max(2, 3)
TypeError: 'float' object is not callable
You could hack yourself out of this
>>> max = __builtins__.max
>>> max
<built-in function max>
>>> max(2, 3)
3
However you should never do this, just chose a different variable name such as max_num
answered Dec 10, 2014 at 9:54
Actually the max() function takes «iterator » as the parameter and returns the maximum value, It is very flexible functions and accepts arguments in the form of:
-
integers:
maximum = max(2,1,4,5,6,9) print maximum
-
lists:
maximum = max([2,1,4,5,6,9])
print maximum
-
strings:
maximum = max(«214569»)
print maximum
-
so these are only some ways of using this function, and yes you can use the max function for the floating numbers in the same way.
maximum = max(1.3,1.5,2.6,4.6)
print maximum
but you cannot pass a single float value or integer value to the function, You should pass any iterable object, with length greater than 1.
And you should avoid using these inbuilt functions as variable names
Hope that helps
answered Dec 10, 2014 at 10:05
ZdaRZdaR
22.1k7 gold badges66 silver badges87 bronze badges
2
If you try to call a float as if it were a function, you will raise the error “TypeError: ‘float’ object is not callable”.
To solve this error, ensure you use operators between terms in mathematical operations and that you do not name any variables “float.
This tutorial will go through how to solve this error with the help of code examples.
Table of contents
- TypeError: ‘float’ object is not callable
- What is a TypeError?
- What Does Callable Mean?
- Example #1
- Solution
- Example #2
- Solution
- Summary
TypeError: ‘float’ object is not callable
What is a TypeError?
TypeError occurs in Python when you perform an illegal operation for a specific data type.
What Does Callable Mean?
Calling a function means the Python interpreter executes the code inside the function. In Python, we can only call functions. We can call functions by specifying the name of the function we want to use followed by a set of parentheses, for example, function_name()
. Let’s look at an example of a working function that returns a string.
# Declare function def simple_function(): print("Hello World!") # Call function simple_function()
Hello World!
We declare a function called simple_function in the code, which prints a string. We can then call the function, and the Python interpreter executes the code inside simple_function().
If we try to call a floating-point number, we will raise the TypeError:
number = 5.6 number()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 number = 5.6 2 ----≻ 3 number() TypeError: 'float' object is not callable
Example #1
Let’s look at an example to prove the sum of squares formula for two values. We define two variables with floating-point values, calculate the left-hand side and right-hand side of the formula, and then print if they are equal.
a = 3.0 b = 4.0 lhs = a ** 2 + b ** 2 rhs = (a + b)(a + b) - 2*a*b print(lhs == rhs)
Let’s run the code to see what happens:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) 2 b = 4.0 3 lhs = a ** 2 + b ** 2 ----≻ 4 rhs = (a + b)(a + b) - 2*a*b 5 print(lhs == rhs) TypeError: 'float' object is not callable
The error occurs because we do not have the multiplication operator * between the two (a + b) terms. The Python interpreter sees this as a call to (a + b) with parameters (a + b).
Solution
We need to put a multiplication operator between the two (a + b) terms to solve the error. Let’s look at the revised code:
a = 3.0 b = 4.0 lhs = a ** 2 + b ** 2 rhs = (a + b)*(a + b) - 2*a*b print(lhs == rhs)
Let’s run the code to see what happens:
True
We get a True
statement, proving that the sum of squares formula works.
Example #2
Let’s look at an example of converting a weight value in kilograms to pounds. We give the conversion value the name “float
” and then take the input from the user, convert it to a floating-point number then multiply it by the conversion value.
float = 2.205 weight = float(input("Enter weight in kilograms: ")) weight_in_lbs = weight * float print(f'{weight} kg is equivalent to {round(weight_in_lbs, 1)} lbs')
Let’s run the code to see what happens:
Enter weight in kilograms: 85 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 float = 2.205 2 ----≻ 3 weight = float(input("Enter weight in kilograms: ")) 4 5 weight_in_lbs = weight * float TypeError: 'float' object is not callable
The error occurs because we assigned the value 2.205 to “float
“. Then we tried to call the built-in float()
method, but float
is now a floating-point number.
Solution
We can name our conversion variable something more meaningful to solve this error. Let’s call it “conversion”. Then we can call the float()
method safely. Let’s look at the revised code:
conversion = 2.205 weight = float(input("Enter weight in kilograms: ")) weight_in_lbs = weight * conversion print(f'{weight} kg is equivalent to {round(weight_in_lbs,1)} lbs')
Let’s run the code to get the result:
Enter weight in kilograms: 85 85.0 kg is equivalent to 187.4 lbs
The program takes the input from the user in kilograms, multiplies it by the conversion value and returns the converted value to the console.
Summary
Congratulations on reading to the end of this tutorial! To summarize, TypeError ‘float’ object is not callable occurs when you try to call a float as if it were a function. To solve this error, ensure any mathematical operations you use have all operators in place. If you multiply values, there needs to be a multiplication operator between the terms. Ensure that you name your float objects after their purpose in the program and not as “float”.
For further reading on “not callable” errors, go to the article: How to Solve Python TypeError: ‘dict’ object is not callable
To learn more about Python, specifically for data science and machine learning, go to the online courses page on Python.
Have fun and happy researching!
Table of Contents
Hide
- What is TypeError: the ‘float’ object is not callable?
- Scenario 1: When you try to call the reserved keywords as a function
- Solution
- Scenario 2: Missing an Arithmetic operator while performing the calculation
- Solution
- Conclusion
The TypeError: ‘float’ object is not callable error occurs if you call floating-point value as a function or if an arithmetic operator is missed while performing the calculations or the reserved keywords are declared as variables and used as functions,
In this tutorial, we will learn what float object is is not callable error means and how to resolve this TypeError in your program with examples.
There are two main scenarios where developers get this TypeError is:
- When you try to call the reserved keywords as a function
- Missing an Arithmetic operator while performing the calculation
Scenario 1: When you try to call the reserved keywords as a function
Using the reserved keywords as variables and calling them as functions are developers’ most common mistakes when they are new to Python. Let’s take a simple example to reproduce this issue.
item_price = [5.2, 3.3, 5.4, 2.7]
sum = 5.6
sum = sum(item_price)
print("The sum of all the items is:", str(sum))
Output
Traceback (most recent call last):
File "c:PersonalIJSCodemain.py", line 3, in <module>
sum = sum(item_price)
TypeError: 'float' object is not callable
If you look at the above code, we have declared the sum as a variable and stored a floating-point value. However, in Python, the sum()
is a reserved keyword and a built-in method that adds the items of an iterable and returns the sum.
Since we have declared sum as a variable and used it as a function to add all the items in the list, Python will throw TypeError.
Solution
We can fix this error by renaming the sum
variable to total_price
, as shown below.
item_price = [5.2, 3.3, 5.4, 2.7]
total_price = 5.6
total_price = sum(item_price)
print("The sum of all the items is:", str(total_price))
Output
The sum of all the items is: 16.6
Scenario 2: Missing an Arithmetic operator while performing the calculation
While performing mathematical calculations, if you miss an arithmetic operator within your code, it leads to TypeError: ‘float’ object is not callable error.
Let us take a simple example to calculate the tax for the order. In order to get the tax value, we need to multiply total_value*(tax_percentage/100)
.
item_price = [5.2, 3.3, 5.4, 2.7]
tax_percentage = 5.2
total_value = sum(item_price)
tax_value = total_value(tax_percentage/100)
print(" The tax amount for the order is:", tax_value)
Output
Traceback (most recent call last):
File "c:PersonalIJSCodemain.py", line 5, in <module>
tax_value = total_value(tax_percentage/100)
TypeError: 'float' object is not callable
We have missed out on the multiplication operator while calculating the tax value in our code, leading to TypeError by the Python interpreter.
Solution
We can fix this issue by adding a multiplication (*) operator to our code, as shown below.
item_price = [5.2, 3.3, 5.4, 2.7]
tax_percentage = 5.2
total_value = sum(item_price)
tax_value = total_value*(tax_percentage/100)
print(" The tax amount for the order is:", tax_value)
Output
The tax amount for the order is: 0.8632000000000002
Conclusion
The TypeError: ‘float’ object is not callable error raised when you try to call the reserved keywords as a function or miss an arithmetic operator while performing mathematical calculations.
Developers should keep the following points in mind to avoid the issue while coding.
- Use descriptive and unique variable names.
- Never use any built-in function, modules, reserved keywords as Python variable names.
- Ensure that arithmetic operators is not missed while performing calculations.
- Do not override built-in functions like
sum()
,round()
, and use the same methods later in your code to perform operations.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
Have you ever seen the TypeError object is not callable when running one of your Python programs? We will find out together why it occurs.
The TypeError object is not callable is raised by the Python interpreter when an object that is not callable gets called using parentheses. This can occur, for example, if by mistake you try to access elements of a list by using parentheses instead of square brackets.
I will show you some scenarios where this exception occurs and also what you have to do to fix this error.
Let’s find the error!
What Does Object is Not Callable Mean?
To understand what “object is not callable” means we first have understand what is a callable in Python.
As the word callable says, a callable object is an object that can be called. To verify if an object is callable you can use the callable() built-in function and pass an object to it. If this function returns True the object is callable, if it returns False the object is not callable.
callable(object)
Let’s test this function with few Python objects…
Lists are not callable
>>> numbers = [1, 2, 3]
>>> callable(numbers)
False
Tuples are not callable
>>> numbers = (1, 2, 3)
>>> callable(numbers)
False
Lambdas are callable
>>> callable(lambda x: x+1)
True
Functions are callable
>>> def calculate_sum(x, y):
... return x+y
...
>>> callable(calculate_sum)
True
A pattern is becoming obvious, functions are callable objects while data types are not. And this makes sense considering that we “call” functions in our code all the time.
What Does TypeError: ‘int’ object is not callable Mean?
In the same way we have done before, let’s verify if integers are callable by using the callable() built-in function.
>>> number = 10
>>> callable(number)
False
As expected integers are not callable 🙂
So, in what kind of scenario can this error occur with integers?
Create a class called Person. This class has a single integer attribute called age.
class Person:
def __init__(self, age):
self.age = age
Now, create an object of type Person:
john = Person(25)
Below you can see the only attribute of the object:
print(john.__dict__)
{'age': 25}
Let’s say we want to access the value of John’s age.
For some reason the class does not provide a getter so we try to access the age attribute.
>>> print(john.age())
Traceback (most recent call last):
File "callable.py", line 6, in <module>
print(john.age())
TypeError: 'int' object is not callable
The Python interpreter raises the TypeError exception object is not callable.
Can you see why?
That’s because we have tried to access the age attribute with parentheses.
The TypeError ‘int’ object is not callable occurs when in the code you try to access an integer by using parentheses. Parentheses can only be used with callable objects like functions.
What Does TypeError: ‘float’ object is not callable Mean?
The Python math library allows to retrieve the value of Pi by using the constant math.pi.
I want to write a simple if else statement that verifies if a number is smaller or bigger than Pi.
import math
number = float(input("Please insert a number: "))
if number < math.pi():
print("The number is smaller than Pi")
else:
print("The number is bigger than Pi")
Let’s execute the program:
Please insert a number: 4
Traceback (most recent call last):
File "callable.py", line 12, in <module>
if number < math.pi():
TypeError: 'float' object is not callable
Interesting, something in the if condition is causing the error ‘float’ object is not callable.
Why?!?
That’s because math.pi is a float and to access it we don’t need parentheses. Parentheses are only required for callable objects and float objects are not callable.
>>> callable(4.0)
False
The TypeError ‘float’ object is not callable is raised by the Python interpreter if you access a float number with parentheses. Parentheses can only be used with callable objects.
What is the Meaning of TypeError: ‘str’ object is not callable?
The Python sys module allows to get the version of your Python interpreter.
Let’s see how…
>>> import sys
>>> print(sys.version())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
No way, the object is not callable error again!
Why?
To understand why check the official Python documentation for sys.version.
That’s why!
We have added parentheses at the end of sys.version but this object is a string and a string is not callable.
>>> callable("Python")
False
The TypeError ‘str’ object is not callable occurs when you access a string by using parentheses. Parentheses are only applicable to callable objects like functions.
Error ‘list’ object is not callable when working with a List
Define the following list of cities:
>>> cities = ['Paris', 'Rome', 'Warsaw', 'New York']
Now access the first element in this list:
>>> print(cities(0))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
What happened?!?
By mistake I have used parentheses to access the first element of the list.
To access an element of a list the name of the list has to be followed by square brackets. Within square brackets you specify the index of the element to access.
So, the problem here is that instead of using square brackets I have used parentheses.
Let’s fix our code:
>>> print(cities[0])
Paris
Nice, it works fine now.
The TypeError ‘list’ object is not callable occurs when you access an item of a list by using parentheses. Parentheses are only applicable to callable objects like functions. To access elements in a list you have to use square brackets instead.
Error ‘list’ object is not callable with a List Comprehension
When working with list comprehensions you might have also seen the “object is not callable” error.
This is a potential scenario when this could happen.
I have created a list of lists variable called matrix and I want to double every number in the matrix.
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[2*row(index) for index in range(len(row))] for row in matrix]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
File "<stdin>", line 1, in <listcomp>
TypeError: 'list' object is not callable
This error is more difficult to spot when working with list comprehensions as opposed as when working with lists.
That’s because a list comprehension is written on a single line and includes multiple parentheses and square brackets.
If you look at the code closely you will notice that the issue is caused by the fact that in row(index) we are using parentheses instead of square brackets.
This is the correct code:
>>> [[2*row[index] for index in range(len(row))] for row in matrix]
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
Conclusion
Now that we went through few scenarios in which the error object is not callable can occur you should be able to fix it quickly if it occurs in your programs.
I hope this article has helped you save some time! 🙂
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
Python supports a distinct data type to store floating points or decimal numbers, and that data type is known as Python float. Floating-point values are the numbers with decimal values, and Float is their data type.
Floating-point values are like other data types present in Python, but they represent decimal numerical values. But if we treat them as a function and call them using parenthesis, we get the
TypeError: ‘float’ object is not callable
Error.
In this Python tutorial, we will discuss this Python error and learn why it raises and how to solve it. We will also discuss some Python code snippet that causes this error and solve them so that you can have a better understanding of this error. So let’s get started with the error itself.
The Python Error
TypeError: 'float' object is not callable
is divided into two statements, Error Type and Error Message, separated with a colon
:
.
-
Error Type
(
TypeError
):
TypeError is one of the most common Python standard exceptions, and it raises when we perform an incorrect operation on a Python object. -
Error Message(
'float' object is not callable
): This is the error message, which tells us that we are calling a Python float object as a function, which is invalid in Python.
Error Reason
Float objects are used in Python to store floating-point numbers, but if we call a float variable as a function by putting a parenthesis after its variable name, we receive the
TypeError: ‘float’ object is not callable
error.
Example
# a floating point number
my_num = 300.23
# call the float number as a function
my_num()
Output
Traceback (most recent call last):
File "main.py", line 5, in <module>
my_num()
TypeError: 'float' object is not callable
Break the Code
In the above example, we are getting the error because when we put the parenthesis
()
after a variable name, Python treats it as a function calling statement. But in the above example,
my_num
it is not a function. It is a float number. That’s why Python threw the error
'float' object is not callable
, which simply means we can not call the float objects functions.
Common Error Example
There are two common major cases when many new Python learners commit the mistake and encounter this error.
-
Scenario 1:
Used float as a variable name and used the
float()
function afterward. -
Scenario 2:
Forget to put the math operator between the opening parenthesis and the float number.
Scenario 1 (Used float as a variable name)
The most common mistake that many new python learners do is when they use the
float
keywords as a variable name to store a floating-point number, and in the same program, they also use the
float()
function to convert an object to a floating-point object.
Example
# define a variable by name float
float = 12.0
height = float(input("Enter your height in inches: "))
foot = height/float
print(f"Your height is: {round(foot,2)} Feet")
Output
Enter your height in inches: 56.4
Traceback (most recent call last):
File "main.py", line 4, in <module>
height = float(input("Enter your height in inches: "))
TypeError: 'float' object is not callable
Break the Code
In the above example, we are trying to convert the user entered height in inches to feet. But we are receiving the
TypeError: 'float' object is not callable
error at line 4.
This is because, in line 2, we have defined a variable by name
float
whose value is
12.0
, that represents the value to convert the inches to feet. But, in line 4, we are using the Python
float()
function to convert the user input height to a floating-point number.
But now for Python
float
is not a function anymore. It is a floating-point variable whose value is 12.0. that is defined in line 2. By which it will not call the actual Python inbuilt function
float().
Instead, it will call the
float
variable a function, which will lead to the
TypeError: 'float' object is not callable
error.
Solution
The solution for the above scenario is very simple. All we need to do is change the name of the
float
variable to something else. This is also very important. While we want to write good code in Python, we never use keywords and function names to define a variable.
Solution 1
# define a variable by name inch
inch = 12.0
height = float(input("Enter your height in inches: "))
foot = height/inch
print(f"Your height is: {round(foot,2)} Feet")
Output
Enter your height in inches: 67.4
Your height is: 5.62 Feet
Scenario 2 (Forget to put the math operator )
In mathematics, if we do not put any operator between the number and the opening parenthesis
(,
then we treat that expression as a multiplication symbol between the number outside the parenthesis and the number inside the parenthesis.
For instance(in mathematics)
2.0(3.0+4.0) = 14.0
But in Python programming, we need to specify the Arithmetic operator between the number and the opening or closing parenthesis; else, we get the error.
for instance (in python)
2.0 (3.0 +4.0) = error
Example
#floating point numberss
a= 2.0
b= 3.0
c= 4.0
#expression
result = a(b+c)
print(result)
Output
Traceback (most recent call last):
File "main.py", line 7, in <module>
result = a(b+c)
TypeError: 'float' object is not callable
Break the code
If we look at the error code statement, we can see that the error occurred on line 7 with the
result = a(b+c)
statement. This is because we forget to put the
*
operator after variable
a
. The Python interpreter mishandles the floating-point variable
a
with the function calling statement.
Solution
The solution to this problem is also very straightforward. All we need to do is place the Arithmetic operator between variable
a
and
(
parenthesis.
solution 2
#floating point numbers
a= 2.0
b= 3.0
c= 4.0
#expression
result = a*(b+c)
print(result)
Output
14.0
Conclusion
In this Python tutorial, we learned what is
TypeError: ‘float’ object is not callable
error in Python and how to solve it. If we look closely at the error message, we can tell that the error is related to the float and calling a function. The only reason this error occurs is when we write a function calling statement using a Python floating-point variable or value.
If you have a basic knowledge of Python floats and functions, debugging this error would be a piece of cake for you. If you are still getting this error in your Python program, you can share your code in the comment section. We will be happy to help you in debugging.
People are also reading:
-
PHP XML Parsing Functions
-
Python NameError name is not defined Solution
-
Best XML Editors
-
Python IndexError: tuple index out of range Solution
-
How to Convert HTML Tables into CSV Files in Python?
-
Python TypeError: unhashable type: ‘slice’ Solution
-
Face Detection in Python
-
Python AttributeError: ‘NoneType’ object has no attribute ‘append’Solution
-
HOG Feature Extraction in Python
-
Python typeerror: ‘list’ object is not callable Solution