Practice With Arithmetic Operators

8. Operator Precedence

In Python, as in mathematics, we need to keep in mind that operators will be evaluated in order of precedence, not from left to right or right to left.

If we look at the following expression:

u = 10 + 10 * 5

We may read it left to right, but remember that multiplication will be done first, so if we call print(u), we will receive the following value:

Output:

60

This is because 10 * 5 evaluates to 50, and then we add 10 to return 60 as the final result.

 

If instead we would like to add the value 10 to 10, then multiply that sum by 5, we can use parentheses just like we would in math:

u = (10 + 10) * 5
print(u)

Output:

100

One way to remember the order of operation is through the acronym PEMDAS:

Order Letter Stands for
1 P Parentheses
2 E Exponent
3 M Multiplication
4 D Division
5 A Addition
6 S Subtraction

You may be familiar with another acronym for the order of operations, such as BEDMAS or BODMAS. Whatever acronym works best for you, try to keep it in mind when performing math operations in Python so that the results that you expect are returned.