The Pythagorean theorem
For a right triangle with legs a and b and hypotenuse c:
a² + b² = c²
If you know two sides, you can find the third. To solve for c, you rearrange: c = √(a² + b²). To solve for a, you rearrange: a = √(c² - b²).
Key idea: A formula is a recipe. Code just follows the recipe with numbers.
Distance between two points
The distance formula comes straight from the Pythagorean theorem. Given two points (x₁, y₁) and (x₂, y₂), the horizontal gap is Δx = x₂ - x₁ and the vertical gap is Δy = y₂ - y₁. The distance is the hypotenuse of that right triangle:
d = √((x₂ - x₁)² + (y₂ - y₁)²)
Writing this in code is almost a direct translation. The only trick is to use ** for powers and math.sqrt for the square root.
Area of a triangle
You probably know the simple area formula: A = ½ bh. But what if you only know the three side lengths? Heron's formula lets you find the area from the sides alone.
First, compute the semi-perimeter s:
s = (a + b + c) / 2
Then the area is:
A = √[s(s - a)(s - b)(s - c)]
This works for any valid triangle. If the three sides cannot form a triangle, the expression under the square root becomes negative, and there is no real area.
Heron's formula step by step
Let us turn Heron's formula into an algorithm:
- Add the three sides and divide by 2 to get s.
- Check that s(s - a)(s - b)(s - c) is not negative.
- Take the square root.
- Return the area.
Notice how each step is small and clear. That is the secret to writing code for math: break every formula into tiny, ordered steps.
Interactive geometry solver
Pick a problem, enter values, and see the computer solve it one step at a time.
Geometry formulas in Python
Here are the three formulas written as functions. Read the code and match each line to a step you already know.
import math def hypotenuse(a, b): return math.sqrt(a**2 + b**2) def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 return math.sqrt(dx**2 + dy**2) def triangle_area(a, b, c): s = (a + b + c) / 2 area_squared = s * (s - a) * (s - b) * (s - c) if area_squared < 0: return "Not a valid triangle" return math.sqrt(area_squared) print(hypotenuse(3, 4)) print(distance(1, 2, 4, 6)) print(triangle_area(3, 4, 5))
5.0 5.0 6.0
Each function names the problem it solves, computes intermediate values like dx, dy, and s, and returns a clear result. You can now use these functions inside bigger programs.
Quick quiz
1. What is the first step in Heron's formula?
2. The distance formula is based on which theorem?
3. If a function returns "Not a valid triangle," what happened in Heron's formula?
Keep learning
Geometry gave us right triangles and distances. Next, use code to explore angles, ratios, and the unit circle in trigonometry.
Part of the “Coding for High School Math” series.