Python - Creating a Pythagorean Theorem Calculator

Pythagorean Theorem

The Pythagorean theorem states that the hypotenuse, c in the image below, is the sum of the squares of the length of the other two other sides in the triangle, a and b. This is typically written as c^2=a^2+b^2. In our program we are going to show not only c^2 but also c, which we will get from the equation c=\sqrt{a^2+b^2}.

Image source: mathblog.com

Pythagorean Theorem Calculator Code

Below is an example code in Python of a Pythagorean theorem calculator. The program lets a user input two values, one for side a and one for side b. When the variables have been fed with numbers they are raised to the power of 2, then c^2 and c are calculated and printed to the screen for the user to observe.

import math

a = int(input('Enter a value for a: '))
b = int(input('Enter a value for b: '))

a2 = pow(a, 2)
b2 = pow(b, 2)
c2 = a2 + b2
c = math.sqrt(c2)

print('c2 = ', c2, '\nc = ', c)
Output:
Enter a value for a: 4
Enter a value for b: 4
c2 =  32 
c =  5.656854249492381


How does it work?

Let us dissect this code line by line. In the first line we have import math. This is needed because when we take the square root of c^2 we use the function sqrt(), which is part of the math library. Have a look at the next two lines with code:

a = int(input('Enter a value for a: '))
b = int(input('Enter a value for b: '))

These two lines are responsible for letting the user input something and store whatever the user typed into the variables a and b. Observe that both input functions are wrapped with int(). We have to tell Python that we want the input to be interpreted as integers, otherwise Python will assume that it is a string we just typed. It would not make sense in this program to store the input as strings since the next lines are using these two variables to do calculations:

a2 = pow(a, 2)
b2 = pow(b, 2)

The variables a2 and b2 are corresponding to a^2 and b^2 in the equation provided at the top of this post. The function pow(), which is short for power, is used to raise a number to a given power. The first parameter is where we type the base we want to raise and the second parameter is for the exponent. In our case, a is raised to 2, and then b is raised to 2. In the next two lines,

c2 = a2 + b2
c = math.sqrt(c2)

we simply add a2 and b2 and store the sum in c2, which corresponds to c^2 in the formula of Pythagorean theorem provided above. We then use this variable to calculate c by taking the square root of c2, which the function math.sqrt() helps us with.

print('c2 = ', c2, '\nc = ', c)

Here the result is printed to the screen.

Author

authors profile photo