Programming Assignment – Unit 4
Part 1: Incremental Development of a Hypotenuse Function
To build a function that computes the length of the hypotenuse of a right-angled triangle, I
followed the incremental development method described in Think Python. Instead of writing the
full function at once, I built it in small steps. This helps identify mistakes early and makes
debugging much easier.
Stage 1: Basic Structure of the Function
At first, I created a simple function containing only placeholders. This allows testing whether the
function can be called without errors.
def hypotenuse(a, b):
# Stage 1: placeholder
return 0
Test:
print(hypotenuse(3, 4))
Output:
This confirms the function runs but does not yet compute anything.
Stage 2: Adding the Squaring Step
Next, I added the step of squaring both sides, which is part of the Pythagorean formula.
def hypotenuse(a, b):
# Stage 2: compute squares
a_sq = a ** 2
b_sq = b ** 2
return a_sq + b_sq
Test:
print(hypotenuse(3, 4))
Output:
25
This output is the sum of squares but not yet the hypotenuse.
Stage 3: Taking the Square Root
Finally, I added the square root to complete the Pythagorean theorem:
hypotenuse = √(a² + b²)
import math
def hypotenuse(a, b):
# Stage 3: complete computation
a_sq = a ** 2
b_sq = b ** 2
total = a_sq + b_sq
return [Link](total)
Final Tests
print(hypotenuse(3, 4))
print(hypotenuse(5, 12))
print(hypotenuse(8, 15))
Outputs:
5.0
13.0
17.0
These results match the well-known Pythagorean triples.
Part 2: Creating My Own Function Using Incremental Development
For my personal portfolio example, I created a function that calculates the final price after
applying a discount and tax rate. This is useful in real-life business software, shopping carts,
and billing systems.
Stage 1: Basic Function Shell
def final_price(price, discount, tax):
return 0
This simply tests that the function runs.
Stage 2: Apply the Discount
def final_price(price, discount, tax):
# Apply discount
discounted = price - (price * discount)
return discounted
Test:
print(final_price(100, 0.10, 0.16))
Output:
90.0
Stage 3: Apply Tax After Discount
def final_price(price, discount, tax):
# Calculate discounted price
discounted = price - (price * discount)
# Apply tax
final = discounted + (discounted * tax)
return final
Final Tests:
print(final_price(100, 0.10, 0.16))
print(final_price(250, 0.20, 0.08))
print(final_price(80, 0.05, 0.10))
Outputs:
104.4
216.0
83.6
Technical Explanation
The function receives three arguments:
price (original cost),
discount (decimal form, e.g., 0.20 for 20%),
tax (decimal form).
First, the discount reduces the price. Then tax is added to the discounted value. Building the
function step-by-step allowed me to confirm that each calculation behaved correctly before
combining them.
Reference
Downey, A. (2015). Think Python: How to Think Like a Computer Scientist. Green Tea Press.
[Link]