Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate Triangle Area: Can a Python function find the area with base and height?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading