We discussed in class three categories of functions. As a class, we have looked At the first two: groups of commands, and parameterized functions.
The third category are functions that return information.
We will revisit the function that we wrote in class to compute the hypotenuse of a right triangle. This function can be written to simply calculate the value and print it, or RETURN the value like an arithmetic operation.
Here are examples of both:
This one calculates the hypotenuse and displays the result to the console:
def calcHypV1(side1, side2):
hyp = math.sqrt(side1**2 + side2**2)
print("The hypotenuse is: ", hyp)
This version calculates the hypotenuse and returns the result to the program:
def calcHypV2(side1, side2):
hyp = math.sqrt(side1**2 + side2**2)
return hyp
The first version is fine if you only want the information to be displayed, and not used in a subsequent calculation. It might be called in this context:
print("Calculate the length of the hypotenuse of a right triangle whose sides are 9 and 21")
calcHyp(9, 21)
The output of this code would be:
The hypotenuse is: 22.847319317591726"
However, this approach would not be helpful if we want to calculate the perimeter (sum of all sides) of the triangle. In this context, it might be called like this:
print("Calculate the perimeter of a right triangle who two sides are 9 and 21")
perimeter = 9 + 21 + calcHypV2(9,21)
print("The perimeter is: ", perimeter)
The output of this code would be:
The perimeter is 52.847319317591726: