In Python, we can calculate the lengths of the sides of a triangle easily using the Pythagorean Theorem.

def pythagoreanTheorem(toSolve,side1,side2):
    if toSolve == "Hypot":
        length = (side1 ** 2 + side2 ** 2) ** (1/2)        
    else: 
        if side2 < side1:
            temp = side2
            side2 = side1
            side1 = temp
        length = (side2 ** 2 - side1 ** 2) ** (1/2)
    return length

print(pythagoreanTheorem("Hypot",3,4))
print(pythagoreanTheorem("Hypot",2.5,9.1))
print(pythagoreanTheorem("Side",4,5))

#Output:
5.0
9.43716058992322
3.0

One of the most famous and well-known math equations is the Pythagorean Theorem. The Pythagorean Theorem states that:

In a right-angled triangle, the square of the hypotenuse side is equal to the sum of squares of the other two sides.

In equation form, we have for a right-angled triangle, that the hypotenuse length is equal to the square of the length of side one and the square of the length of side two.

Using Python, we can easily implement the Pythagorean Theorem.

To create a function which will apply the Pythagorean Theorem in Python, we just need to know which side to solve for.

If we are solving for the length of the hypotenuse, then the formula in Python is the square root of the sum of squared side lengths:

hypotenuse_length = (side1_length ** 2 + side2_length ** 2) ** (1/2)

If we are solving for the length of one of the sides of the triangle, then the formula in Python is:

side1_length = (hypotenuse_length ** 2 - side2_length ** 2) ** (1/2)

Below is a function which will has three arguments which will allow us to use the Pythagorean Theorem in Python. The three arguments are the side we want to solve for, and two lengths.

def pythagoreanTheorem(toSolve,side1,side2):
    if toSolve == "Hypot":
        length = (side1 ** 2 + side2 ** 2) ** (1/2)        
    else: 
        if side2 < side1:  #order matters here, so we can make the hypotenuse the bigger length
            temp = side2
            side2 = side1
            side1 = temp
        length = (side2 ** 2 - side1 ** 2) ** (1/2)
    return length

print(pythagoreanTheorem("Hypot",3,4))
print(pythagoreanTheorem("Hypot",2.5,9.1))
print(pythagoreanTheorem("Side",4,5))

#Output:
5.0
9.43716058992322
3.0

Hopefully this article has been helpful for you to learn how to use the Pythagorean Theorem in Python to get the lengths of the sides of a triangle.

Categorized in:

Python,

Last Update: March 20, 2024