# Order of Operations in Python

You must have heard the phrase ‘Order of Operations’ in math class. Now, this may have been in middle school or not, it doesn’t matter. This Order of Operations is called BODMAS (Bracket, Order, Division, Multiplication, Addition, Subtraction), BIDMAS (Bracket, Indices, Division, Multiplication, Addition, Subtraction) or PEMDAS (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction) depending on where you’re from. So, whatever the acronym you must have been taught with, it is generally known that the Order of Operations must be followed in order to get correct answers when solving or simplifying mathematical expressions.

The Python programming language uses this Order of Operations to execute codes that solve math problems. Therefore, it is important to follow the Order of Operations when writing Python codes for your code to be executed correctly and for Python to give accurate output.

Let’s take a look at how the Order of Operations works in Python with a small example. Say we want to write a code to calculate the 2-dimensional distance between two points: 

Q = (1, 3) and P = (2, 5)

We know that the formula for the distance between two points is:
d = √(x2 - x1)2 + (y2 - y1)2

Converting the above formula to Python code, we have:

```from math import sqrt
     Q = [1, 3]
     P = [2, 5]
     d = sqrt((Q[0] - P[0]) ** 2 + (Q[1] - P[1]) ** 2)
     print(d)
```. Output =2.23606797749979. From the above code and output, let’s analyze how Python must have executed the code. What Python did was to firstly execute the expression before the ‘+’ sign in the order:
 
```Q[0] - P[0], (Q[0] - P[0]) ** 2
``` , next is the expression after the ‘+’ sign in the order: 

```Q[1] - P[1], (Q[1] - P[1]) ** 2
``` 
. Finally, it adds the result of the two expressions together giving the output as above.

In summary, Python executes code in the order expressions inside of the parentheses first before expressions outside of the parentheses. So, when next you’re writing Python codes to solve or simplify mathematical expressions, keep the math Order of Operations in mind!

