Part 1: Calculating Hypotenuse Length
Stage 1: Define the Problem and Function Signature
The problem requires calculating the length of a right triangle's hypotenuse given two legs' lengths.
We'll define a function `hypotenuse(a, b)`.
Stage 2: Implement the Calculation
We'll use the Pythagorean theorem: c² = a² + b², where c is the hypotenuse.
import math
def hypotenuse(a, b):
# Calculate the square of each leg
a_squared = a ** 2
b_squared = b ** 2
# Calculate the sum of squares
sum_squares = a_squared + b_squared
# Calculate the square root
c = math.sqrt(sum_squares)
return c
Stage 3: Testing
# Test 1: hypotenuse(3, 4)
print(hypotenuse(3, 4)) # Output: 5.0
# Test 2: hypotenuse(5, 12)
print(hypotenuse(5, 12)) # Output: 13.0
# Test 3: hypotenuse(8, 15)
print(hypotenuse(8, 15)) # Output: 17.0
Part 2: Custom Function - Calculating Circle Area
Stage 1: Define the Problem and Function Signature
Create a function `circle_area(radius)` calculating a circle's area.
Stage 2: Implement the Calculation
We'll use the formula: A = πr².
import math
def circle_area(radius):
# Validate input
if radius < 0:
raise ValueError("Radius cannot be negative")
# Calculate area
area = math.pi * (radius ** 2)
return area
Stage 3: Testing
# Test 1: circle_area(5)
print(circle_area(5)) # Output: 78.53981633974483
# Test 2: circle_area(10)
print(circle_area(10)) # Output: 314.1592653589793
# Test 3: circle_area(15)
print(circle_area(15)) # Output: 707.1067811865476
References:
1. Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,
Massachusetts: Green Tree Press.
( https://greenteapress.com/thinkpython2/thinkpython2.pdf )
2. Python Documentation. (n.d.). Math Module.
(https://bugs.python.org/file47781/Tutorial_EDIT.pdf)