How to Solve the Pythagorean Theorem with a Python Script

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.

🐍 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.

More Topics

Hello! I'm a gaming enthusiast, a history buff, a cinema lover, connected to the news, and I enjoy exploring different lifestyles. I'm Yaman Şener/trioner.com, a web content creator who brings all these interests together to offer readers in-depth analyses, informative content, and inspiring perspectives. I'm here to accompany you through the vast spectrum of the digital world.

Leave a Reply

Your email address will not be published. Required fields are marked *