As an exercise, use incremental development to write a function called hypotenuse that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments. Record each stage of the development process as you go.
After the final stage of development, print the output of hypotenuse(3, 4) and two other calls to hypotenuse with different arguments.
Include all of the following in your Learning Journal:
# Importing the function to extract the square root from the module math
from math import sqrt
# Let's declare a function with parameters a,b -the length of the legs
def hypotenuse(a, b):
# Checking the legs for a positive value
if (a<0 or b<0):
return "Incorrect data entry"
# Formula for calculating the hypotenuse
c = sqrt(a**2 + b**2)
# Returning the value of the function
return c
# Function test with parameters a = 3 b=4
assert hypotenuse(3, 4) == 5, "Should be 5"
# Calculation and output of the hypotenuse for different values of the legs
a, b = 3, 4
print(f'For a triangle with legs {a} and {b} hypotenuse= {hypotenuse(a, b)}')
a, b = 5, 12
print(f'For a triangle with legs {a} and {b} hypotenuse= {hypotenuse(a, b)}')
a, b = 8, 15
print(f'For a triangle with legs {a} and {b} hypotenuse= {hypotenuse(a, b)}')
Comments
Leave a comment