Подскажите. когда пишу вот такой код
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
76.4k6 золотых знаков51 серебряный знак117 бронзовых знаков
задан 14 июн 2018 в 10:27
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
gil9redgil9red
76.4k6 золотых знаков51 серебряный знак117 бронзовых знаков
2
-
p(...)
— вызов объекта p как функции с аргументом из скобок -
p*(...)
— умножение p на результат выражения в скобках.
insolor
46k16 золотых знаков54 серебряных знака95 бронзовых знаков
ответ дан 8 дек 2018 в 21:14
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
46k16 золотых знаков54 серебряных знака95 бронзовых знаков
ответ дан 19 янв 2019 в 0:58
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.
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.