Back

More functions for triangles - Answers

Q1. Get this code working in Python:

1    #Calculate the area of a triangle from the base and height
2
    import math
3    def area_bh(base, height):  # This function has two parameters.
4        '''Calculates the area of a triange from the base and height.
5        Requires two float arguments to work and returns a single float.'''
6        area = 0.5 * base * height
7        return area #This is the answer 'returned' from the function
8

9    myBase = float(input('Please enter the base >>> ')) #get the base
10  myHeight = float(input('Please enter the height >>> ')) #get the height
11  triangle = area_bh(myBase, myHeight) #call the function area_bh and pass it two arguments.
12  print(triangle)

Q2. The program imports the math module, although it isn't used yet. It then works out the perimeter of a triangle from three sides.
Q3 - Q5. Heron's formula calculates the area of a triangle from its three sides. It was 'discovered' by Heron (Hero) around the 60AD (there is some debate about this). The first step is to calculate the perimeter of a triangle and then half it to give a value p. The second step is to work out sqrt((p(p-side1)(p-side2)(p-side3)).
Q6. Research - Google Python 3 math module.
Q7. To find the square root of 300 and store it in a variable called 'answer':  answer = math.sqrt(300)
Q8 - Q10 and the extension work
 To write a program that asks the user to enter in three numbers and then returns both the perimeter of the triangle and the area:

#Calculate the perimeter and area of a triangle from the three sides
import math
def per(side1, side2, side3):
    '''Calculates the perimeter of a triange from the three sides.
    Requires three float arguments to work and returns a single float.'''
    perimeter = side1 + side2 + side3
    return perimeter #This is the answer 'returned' from the function

def area(side1, side2, side3, Perimeter):
    '''Calculates the area of a triange from the three sides using Heron's formula.
    Requires four float arguments to work and returns a single float.'''

    step1 = 0.5*Perimeter
    areaTriangle = math.sqrt(step1*(step1-mySide1)*(step1-mySide2)*(step1-mySide3))
    return areaTriangle

units = input('What units are you using? >>> ')
print('\nCalculate the perimeter and area of a triange >>> ')
mySide1 = float(input('Please enter the length of first side >>> '))
mySide2 = float(input('Please enter the length of second side >>> '))
mySide3 = float(input('Please enter the length of third side >>> '))
myPerimeter = per(mySide1, mySide2, mySide3)
print('The perimeter is',round(myPerimeter,3),units)

print('\n')
areaTriangle = area(mySide1, mySide2, mySide3, myPerimeter)
print('The area of the triangle is ',round(areaTriangle,3),units, 'squared') 

Back