6 Basic Maths Formulas You Can Write in Python Part 1: The Pythagoras Theorem

6 Basic Maths Formulas You Can Write in Python Part 1: The Pythagoras Theorem

Transforming logical statements to code is basically what programmers do.

Since mathematical equations are logical statements, they can be transformed into codes and then, be executed to solve problems.

You won't need an in-depth understanding of this theorem to write the equivalent code for it.

All you need is a logical and arithmetic mindset.

Let's begin!

The Pythagoras: c² = a² + b²

In English: The square of the variable c is equal to the sum of the square of the variables a & b.

This means that to find the variable c, we have to find the squares of a and b. Then we add their squares and find the square root of the resulting value.

See what those variables a, b and c actually represents here

Alright.

Doing all this in a Python function would look like this:

import math

# define the function with no arguments passed
def pythagoras():

    #prompt the user to enter the values for a and b
    print("Please input the values for a and b below:")
    a = int(input("a: "))
    b = int(input("b: "))

    # find the squares the variables, a and b
    square_of_a = math.pow(a,2)
    square_of_b = math.pow(b,2)

    # find the square roots of the addition of their squares and assign the result to a variable c
    c = math.sqrt(square_of_a + square_of_b)

    # return the value of c
    return ("The value for c is: %s" % c)

print(pythagoras())

We imported the math module. This makes it possible for us to use two of its methods. The .pow() and .sqrt() methods.

I wrote an article on Functions & Methods here

Pretty easy right? I told you so.

One fun thing about doing this is that this is just one approach to take.

You can decide to make the pythagoras function accepts parameters, thereby asking for user input outside of the function.

Making it accept parameters is a better practice because it makes the pythagoras function reusable in other instances.

Even more interesting is that you can add conditional statements to the code to allow for cases where the value for the variable c is given and we need to find either a or b.

What a fun way to test your coding prowess. It's up to you now.

Next up is the Quadratic Equation.

Please leave a reaction or a comment or even a question if you have one. Thanks

You can be notified when I post another fun article like this by SUBSCRIBING TO MY NEWSLETTER