Applying the Pythagorean Theorem with Python
The Pythagorean Theorem is a fundamental concept in geometry, stating that in a right-angled triangle, the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides (legs). This theorem is expressed as: a² + b² = c² , where ‘a’ and ‘b’ are the lengths of the legs and ‘c’ is the length of the hypotenuse.
Example 1: Basic Calculation
Let’s start with a simple example to calculate the hypotenuse of a right-angled triangle when we know the lengths of the two legs.
import math
def calculate_hypotenuse(a, b):
"""
Calculates the hypotenuse of a right-angled triangle using the Pythagorean theorem.
Args:
a: Length of one leg of the triangle.
b: Length of the other leg of the triangle.
Returns:
The length of the hypotenuse.
"""
if a < 0 or b < 0:
return "Invalid input: Leg lengths must be non-negative."
c_squared = a2 + b2
c = math.sqrt(c_squared)
return c
# Get input from the user
try:
leg_a = float(input("Enter the length of leg a: "))
leg_b = float(input("Enter the length of leg b: "))
except ValueError:
print("Invalid input: Please enter numbers only.")
exit()
# Calculate the hypotenuse
hypotenuse = calculate_hypotenuse(leg_a, leg_b)
# Print the result
if isinstance(hypotenuse, str):
print(hypotenuse)
else:
print("The length of the hypotenuse is:", hypotenuse)
Explanation:
- We import the `math` module to use the `sqrt()` function for calculating the square root.
- We define a function `calculate_hypotenuse(a, b)` that takes the lengths of the two legs as input.
- We include input validation to check if `a` and `b` are non-negative. If not, we return an error message.
- We calculate `c_squared` using the Pythagorean theorem.
- We calculate `c` using the `math.sqrt()` function.
- We get the input from the user and convert it to floating-point numbers using `float()`. We use a `try-except` block to handle potential `ValueError` exceptions if the user enters non-numeric input.
- We call the `calculate_hypotenuse()` function with the leg lengths.
- We print the result.
Common Mistakes and Corrections:
- Mistake: Not handling invalid input (non-numeric input). Correction: Using a `try-except` block to catch `ValueError` and provide a helpful error message.
- Mistake: Not importing the `math` module. Correction: Adding `import math` at the beginning of the script.
# Example Usage:
leg_a = 3.0
leg_b = 4.0
hypotenuse = calculate_hypotenuse(leg_a, leg_b)
print("The length of the hypotenuse is:", hypotenuse)
Output:
Enter the length of leg a: 3.0
Enter the length of leg b: 4.0
The length of the hypotenuse is: 5.0
Example 2: User Input with Error Handling
This example focuses on robust user input, ensuring that the input is valid before calculating the hypotenuse. It demonstrates more detailed error handling.
import math
def calculate_hypotenuse(a, b):
"""Calculates hypotenuse, handles invalid input."""
if a < 0 or b < 0:
return "Error: Leg lengths must be non-negative."
c_squared = a2 + b2
c = math.sqrt(c_squared)
return c
while True:
try:
leg_a = float(input("Enter the length of leg a (or 'q' to quit): "))
if leg_a == 'q':
break
leg_b = float(input("Enter the length of leg b: "))
result = calculate_hypotenuse(leg_a, leg_b)
if isinstance(result, str):
print(result)
else:
print("The length of the hypotenuse is:", result)
except ValueError:
print("Invalid input. Please enter numbers or 'q' to quit.")
Output:
Enter the length of leg a (or 'q' to quit): 3
Enter the length of leg b: 4
The length of the hypotenuse is: 5.0
Enter the length of leg a (or 'q' to quit): 5
Enter the length of leg b: 12
The length of the hypotenuse is: 13.0
Enter the length of leg a (or 'q' to quit): abc
Invalid input. Please enter numbers or 'q' to quit.
Enter the length of leg a (or 'q' to quit): q
Example 3: Calculating and Displaying Intermediate Values
This example shows how to calculate and display the intermediate values (a², b², and c²) during the process, aiding in understanding the theorem.
import math
def calculate_hypotenuse(a, b):
"""Calculates hypotenuse and intermediate values."""
if a < 0 or b < 0:
return "Error: Leg lengths must be non-negative."
c_squared = a2 + b2
c = math.sqrt(c_squared)
return a, b, c_squared, c
leg_a = 5
leg_b = 12
a, b, c_squared, c = calculate_hypotenuse(leg_a, leg_b)
print("Leg a:", a)
print("Leg b:", b)
print("Square of hypotenuse (c²):", c_squared)
print("Hypotenuse (c):", c)
Output:
Leg a: 5
Leg b: 12
Square of hypotenuse (c²): 144
Hypotenuse (c): 12.0



Leave a Reply