The cause of the error is already more than clear, the operator *
lack in the Heron formula in s(s-a)...
when it should be s*(s-a)...
. When doing s()
you are making a call attempt, when s
is an integer you get the commented error. However the code shown is for Python 2 and this implies having two more things in mind:
-
You should never use input
in Python 2 for user entries lightly. input
evaluates all valid Python code that is entered, which means a wide-open door for code injection attacks. Maybe in cases like this it seems not to have much importance, but it is still a very bad practice. Instead, in Python 2.x you should use raw_input
(which returns a string similar to what input
does in Python 3) and make an explicit cast.
-
The division operator ( /
) works very differently in Python 2 and in Python 3. In Python 3, the result of the actual division (5/2 => 2.5) always returns. In Python 2 the return depends on the type of the operands, for example 5/2 results in 2 (whole division) because both operands are integers, whereas 5 / 2.0 returns us 2.5 .
If you cast a int of your entries and enter a = 3, b= 3, c = 5
you would have a problem since the semiperimeter will be 5 and the area will be 0.0, which is far from the 4.1457 ...
On the other hand, according to the triangular inequality theorem, a triangle is valid if the sum of any two sides is always greater than the remaining side. Just check one of the three possibilities in the if
, the triangle a = 3, b = 12, c = 3
meets a + b >= c
but it is an invalid triangle.
With all this, if you want to be able to enter decimal values for the measures of the sides you can do:
# -*- coding: cp1252 -*-
import math
a = float(raw_input("Ingrese a: "))
b = float(raw_input("Ingrese b: "))
c = float(raw_input("Ingrese c: "))
if ((a + b) > c) and ((a + c) > b) and ((b + c) > a):
s = (a + b + c) / 2
raiz = math.sqrt(s*(s-a)*(s-b)*(s-c))
print raiz
else:
print "El triángulo no es posible"
If you only want to accept integers then do:
# -*- coding: cp1252 -*-
import math
a = int(raw_input("Ingrese a: "))
b = int(raw_input("Ingrese b: "))
c = int(raw_input("Ingrese c: "))
if ((a + b) > c) and ((a + c) > b) and ((b + c) > a):
s = (a + b + c) / 2.0 # Observa el 2.0 en vez de 2
raiz = math.sqrt(s*(s-a)*(s-b)*(s-c))
print raiz
else:
print "El triángulo no es posible"