Practice With Arithmetic Operators
Practice these programming examples to internalize these concepts.
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:
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, then multiply that sum by
5, we can use parentheses just like we would in math:
u = (10 + 10) * 5 print(u)
One way to remember the order of operation is through the acronym PEMDAS:
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.