Float object is not callable ошибка

Подскажите. когда пишу вот такой код

a = int(input())
b = int(input())
c = int(input())
p = (a + b + c)/2
S = p(p - a)(p - b)(p - c)
math.sqrt(S)
print(S)

выдает ошибку TypeError: ‘float’ object is not callable
это наверняка что-то простое, но я никак не могу в чем же дело. Заранее благодарю

gil9red's user avatar

gil9red

76.6k6 золотых знаков53 серебряных знака120 бронзовых знаков

задан 14 июн 2018 в 10:27

alexoks1818's user avatar

3

Ошибка в S = p(p - a)(p - b)(p - c)

p содержит вещественное значение (float)

А p(p - a) синтаксис вызова объекта как функции.

Думаю, правильный код будет такой:

S = p * (p - a) * (p - b) * (p - c)

ответ дан 14 июн 2018 в 10:33

gil9red's user avatar

gil9redgil9red

76.6k6 золотых знаков53 серебряных знака120 бронзовых знаков

2

  • p(...) — вызов объекта p как функции с аргументом из скобок

  • p*(...) — умножение p на результат выражения в скобках.

insolor's user avatar

insolor

47.1k17 золотых знаков56 серебряных знаков99 бронзовых знаков

ответ дан 8 дек 2018 в 21:14

Ivan Trechyokas's user avatar

a = int(input())
b = int(input())
c = int(input())
p = (a + b + c)/2
S = (p * (p - a) * (p - b) * (p - c)) ** 0.5
# необходимо поставить знаки умножения
# корень можно вычислить как число в степени 1/2 т.е. ** 0.5
print(S)

insolor's user avatar

insolor

47.1k17 золотых знаков56 серебряных знаков99 бронзовых знаков

ответ дан 19 янв 2019 в 0:58

Pavel Shuvalov's user avatar

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
  1. What is TypeError: the ‘float’ object is not callable?
  2. Scenario 1: When you try to call the reserved keywords as a function
    1. Solution
  3. Scenario 2: Missing an Arithmetic operator while performing the calculation
    1. Solution
  4. 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:

  1. When you try to call the reserved keywords as a function
  2. 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:\Personal\IJS\Code\main.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:\Personal\IJS\Code\main.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.

Avatar Of Srinivas Ramakrishna

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.

Cover image for How to fix “TypeError: ‘float’ object is not callable” in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “TypeError: ‘float’ object is not callable” error occurs when you try to call a floating-point number (float object) as if it was a function!

Here’s what the error looks like:

Traceback (most recent call last):
  File "/dwd/sandbox/test.py", line 8, in 
    sum += sum(values) # we're calling 88.6()
           ^^^^^^^^^^^
TypeError: 'float' object is not callable

Enter fullscreen mode

Exit fullscreen mode

Calling a floating-point number as if it’s a callable isn’t what you’d do on purpose, though. It usually happens due to a wrong syntax or overriding a function name with a floating-point number.

Let’s explore the common causes and their solutions.

How to fix TypeError: ‘float’ object is not callable?

This TypeError happens under various scenarios:

  1. Declaring a variable with a name that’s also the name of a function
  2. Calling a method that’s also the name of a property
  3. Calling a method decorated with @property
  4. Missing a mathematical operator after a floating-point number

Declaring a variable with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as int, float, dict, list, etc.

All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, sum() refers to the __builtins__.sum() function.

That said, overriding a function (accidentally or on purpose) with a floating-point number is technically possible.

For instance, if you define a variable named sum and assign it to the value of 88.6, it’ll no longer point to __builtins__.sum().

values = [34, 43.5, 2, 8.1, 1]

sum = sum(values) # ⚠️ The value of sum is 88.6 from now on 
# it's no longer pointing the built-in function sum

values = [34, 12]
# ⛔ Raises TypeError: 'float' object is not callable
sum += sum(values) # we're calling 88.6()

Enter fullscreen mode

Exit fullscreen mode

If you run the above code, Python will complain with a «TypeError: ‘float’ object is not callable» error because 88.6 (the new value of sum) isn’t callable.

You have two ways to fix the issue:

  1. Rename the variable sum
  2. Explicitly access the sum function from the builtins module (__bultins__.sum)

The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open():

# Custom open() function using the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...

Enter fullscreen mode

Exit fullscreen mode

In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.

So the above example could be fixed like this:

values = [34, 43.5, 2, 8.1, 1]
sum_of_values = sum(values) 

values = [34, 12]
sum_of_values += sum(values)

print(sum_of_values)
# Output: 134.6

Enter fullscreen mode

Exit fullscreen mode

Here’s another example with the built-in max() function:

items = [1, 45, 54, 165.3, 0, 2]
max = max(items) # max = 165.3

# ...

# ⛔ Raises "TypeError: 'float' object is not callable"
print(max(12, max))

Enter fullscreen mode

Exit fullscreen mode

And to fix it, we rename the max variable name to max_value:

items = [1, 45, 54, 165.3, 0, 2]
max_value = max(items) # max = 165.3

# ...

print(max(12, max_value))
# Output: 165.3

Enter fullscreen mode

Exit fullscreen mode

Another common reason is accidentally overriding the range() function with a floating-point value before using it in a for loop:

range = 34.5

# some code here

# ⛔ Raises "TypeError: 'float' object is not callable"
for i in range(0, 10):
print(i)

Enter fullscreen mode

Exit fullscreen mode

To fix it, we rename the range variable:

range_start = 34.5

# some code here

for i in range(0, 10):
print(i)

Enter fullscreen mode

Exit fullscreen mode

⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!

Overriding functions (and calling them later on) is the most common cause of this type error. It’s similar to calling integer numbers as if they’re callables.

Now, let’s get to the less common mistakes that lead to this error.

Calling a method that’s also the name of a property: When you define a property in a class constructor, any further declarations of the same name (e.g., methods) will be ignored.

class Book:
    def __init__(self, book_title, book_price):
        self.title = book_title
        self.price = book_price

    def price(self):
        return self.price

book = Book('Head First Python', 49.5)

# ⛔ Raises "TypeError: 'float' object is not callable"
print(book.price())

Enter fullscreen mode

Exit fullscreen mode

In the above example, since we have a property named price, the method price() is ignored. As a result, any reference to the price will return the property price. Obviously, calling price() is like calling 49.5(), which raises the type error.

To fix this TypeError, we need to change the method name:

class Book:
    def __init__(self, book_title, book_price):
        self.title = book_title
        self.price = book_price

    def get_price(self):
        return self.price

book = Book('Head First Python', 49.5)

print(book.get_price())
# Output: 49.5

Enter fullscreen mode

Exit fullscreen mode

Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name.

class Book:
    def __init__(self, book_title, book_price):
        self._title = book_title
        self._price = book_price

    @property
    def price(self):
        """Get the book price"""
        return self._price

book = Book('Head First Python', 49.5)

# ⛔ Raises "TypeError: 'float' object is not callable"
print(book.price())

Enter fullscreen mode

Exit fullscreen mode

You need to access the getter method without the parentheses:

book = Book('Head First Python', 49.5)

print(book.price)
# Output: 49.5

Enter fullscreen mode

Exit fullscreen mode

Missing a mathematical operator after a float variable: In algebra, we can remove the multiplication operator to avoid ambiguity in our expressions. For instance, a × b, can be ab, or a × (b + c) can become a(b + c).

But not in Python!

In the above example, if you remove the multiplication operator in a * (b + c), Python’s interpreter would consider it a function call! And since the value of a is numeric (a floating-point number in this case), it’ll raise the error.

So if you have something like this in your code:

a = 12.5
b = 12
c = 87

# ⛔ raises  TypeError: 'float' object is not callable
result = a (b + c)

Enter fullscreen mode

Exit fullscreen mode

You’d have to change it like so:

a = 12.5
b = 12.3
c = 34.7

result = a * (b + c)

print(result)
# Output: 587.5

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Alright, I think it does it! I hope this quick guide helped you fix your problem.

Thanks for reading.

❤️ You might like:

  • How to fix «TypeError: ‘float’ object is not callable» in Python
  • TypeError: ‘int’ object is not callable in Python (Fixed)
  • TypeError: can only concatenate str (not “float”) to str (solutions)
  • TypeError: can only concatenate str (not “int”) to str (Solutions)
  • TypeError: can only concatenate str (not «bool») to str (Fixed)

One error that you might encounter when working with Python is:

TypeError: 'float' object is not callable

This error occurs when you mistakenly call a float object as if it was a function.

The following code is an example that causes this error:

There are three possible scenarios that cause this error:

  1. You attempt to multiply a float without adding the * operator
  2. You override the float() function with a float object
  3. You have a function and a float variable with the same name

This tutorial shows how to reproduce the error in each scenario and how to fix it.

1. You attempt to multiply a float without adding the * operator

First, you declared a simple float variable as follows:

Next, you attempt to multiply the float variable with a number acquired from math operations as follows:

Output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    x = my_float(5 - 2)
        ^^^^^^^^^^^^^^^
TypeError: 'float' object is not callable

The error occurs because you’re adding parentheses next to a float object.

While the above is a valid multiplication formula in real life, this makes Python thinks you’re trying to call a function named my_float() instead of trying to do a multiplication.

To resolve this error, you need to make sure that you’re not adding parentheses next to a float object.

Since you want to multiply the variable, add the multiplication operator * as follows:

my_float = 7.2

x = my_float * (5 - 2)

print(x)  # 21.6

This time, the multiplication succeeds and we didn’t receive an error.

2. You override the float() function with a float object

The built-in function named float() is used to convert an object of another type into a float object.

For example, here’s how to convert a string into a float:

my_string = "7.55"

my_float = float(my_string)
print(my_float)  # 7.55

If you mistakenly create a variable named float, then the float() function would be overwritten.

When you call the float() function, the error would occur as follows:

float = 3.45

another_float = float("7.55")

Output:

Traceback (most recent call last):
  File "/main.py", line 3, in <module>
    another_float = float("7.55")
                    ^^^^^^^^^^^^^
TypeError: 'float' object is not callable

Because you created a variable named float, the float() function gets replaced with that variable, causing you to call a float object instead of the built-in function.

To avoid this error, you need to declare the variable using another name:

my_float = 3.45  # ✅

another_float = float("7.55")

This way, the keyword float would still point to the float function, and the error won’t be raised.

You have a function and a float variable with the same name

Suppose you have a function named get_name() that returns a string as follows:

def get_name():
    return "Nathan"

Then down the line, you declared a variable using get_name as the identifier:

This cause the get_name variable to shadow the get_name() function. When you try to call the function, Python thinks you’re calling the variable instead:

def get_name():
    return "Nathan"

get_name = 7.67

res = get_name()  # TypeError: 'float' object is not callable

To resolve this error, make sure that there’s no duplicate name in your source code.

Each function and variable must have a unique name:

def get_name():
    return "Nathan"

x = 7.67

res = get_name()  # ✅

Now that the name for the function and the variable are unique, we didn’t receive any error.

Conclusion

The TypeError: 'float' object is not callable occurs in Python when you call a float object using parentheses like it’s a function.

To resolve this error, you need to make sure that you’re not calling a float object in your source code.

I hope this tutorial helps. Happy coding!

Понравилась статья? Поделить с друзьями:
  • Filezilla выдает критическую ошибку
  • Filezilla ошибка 110
  • Filezilla невозможно подключиться к серверу ps3 ошибка
  • Filezilla критическая ошибка при передаче файлов 550
  • Filezilla инициализирую tls ошибка невозможно подключиться к серверу