Write a function triangle_area(base, height) that takes the base and height of a triangle as input and returns the area of the triangle.
this is the code I wrote in py
def triangle_area(base, height):
area = (base*height) / 2
in1 = int(area)
flo1 = float(area)
i = 0
x = 0
s = str(area)
while i < len(s):
if (s[i]) == ".":
x += 1
i += 1
else:
i += 1
if x > 0:
print(in1)
elif x == 0:
print(flo1)
it is supposed to output an int when there is no remainder (like 31), and when it isn’t a perfect whole number, it is supposed to output a float (like 31.5)
the problem is that when i run the code, it always outputs an int, and not a float, like if the numbers are 7 and 9, it is supposed to output 31.5, but instead it outputs 31, so why is this?
>Solution :
You can use the built-in float method is_integer():
def triangle_area(base, height):
area = (base * height) / 2
return int(area) if area.is_integer() else area