Returning a Value from a Function

This code demonstrates a function with a return value. Not much harder than a function without.

heronsformula.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from __future__ import print_function, division
import math

def main():
    a = triArea(3, 3, 3)
    print("A triangle with sides 3,3,3 has area {}".format(a))

    a = triArea(3, 4, 5)
    print("A triangle with sides 3,4,5 has area {}".format(a))
    g = triArea(7, 8, 9)
    print("A triangle with sides 7,8,9 has area {}".format(g))

    print("A triangle with sides 5,12,13 has area", triArea(5, 12, 13))
    print("A triangle with sides 10,9,11 has area", triArea(10, 9, 11))
    print("A triangle with sides 8,15,17 has area", triArea(8, 15, 17))


def triArea(a, b, c):
    """Returns the area of a triangle with side lengths a, b and c"""
    s = (a+b+c) / 2
    A = math.sqrt( s*(s-a)*(s-b)*(s-c) )

    # After computing the area, you must "return" the computed value:
    return A

if __name__ == "__main__":
    main()

What You Should See

A triangle with sides 3,3,3 has area 3.89711431703
A triangle with sides 3,4,5 has area 6.0
A triangle with sides 7,8,9 has area 26.83281573
A triangle with sides 5,12,13 has area 30.0
A triangle with sides 10,9,11 has area 42.4264068712
A triangle with sides 8,15,17 has area 60.0

So explanation yet, sorry. Hopefully the code is enough. If you're already this far into the assignments, the code is probably enough.

Study Drills

  1. Add code that uses the function to find the area of a triangle with sides 9, 9, and 9.



©2017 Graham Mitchell