Do you remember the Pythagorean Theorem from math class? It’s a fundamental formula for right triangles that states $a^2 + b^2 = c^2$. We can easily translate this into a Python program that calculates the length of the hypotenuse (the longest side, ‘c’) when we know the lengths of the other two sides.
Table of Contents
🐍 Setting Up the Program
First, our program needs to get the lengths of the two shorter sides, ‘a’ and ‘b’, from the user. We’ll use the input()
function for this. Since the lengths can be decimal numbers, we’ll convert the user’s input to floating-point numbers using the float()
function.a = float(input("Enter the length of the first side: "))
b = float(input("Enter the length of the second side: "))
➗ The Core Calculation
The formula to find the hypotenuse is $c = \sqrt{a^2 + b^2}$. To perform this calculation in Python, we’ll need two things: the exponentiation operator (**
) to square the numbers, and the square root function. The square root function, sqrt()
, isn’t built-in by default; it’s located in the math
module. So, we need to import it at the beginning of our script with import math
. The calculation then becomes: c = math.sqrt(a**2 + b**2)
.
📢 Displaying the Final Result
Once the calculation is complete, the final step is to display the length of the hypotenuse to the user. We can use an f-string to create a clear and readable output message.print(f"The length of the hypotenuse is {c}.")
. You can also format the result to a specific number of decimal places, like {c:.2f}
, for a cleaner look.
This simple program is a perfect example of how you can use Python to solve real-world math problems quickly and accurately. It combines user input, mathematical operations, and module imports into a practical tool.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
- Python Coding Essentials: Reliability by Abstraction
- Python Coding Essentials: Different Types of Data
- Python Coding Essentials: Embrace Storage and Persistence
- Python Coding Essentials: Neater Code with Modules
- Python Coding Essentials: Lock Down with Data Encryption
- Python Coding Essentials: Files and Modules Done Quickly
- Python’s Itertools Module – How to Loop More Efficiently