Python Example with PEMDAS
Python Example with PEMDAS
PEMDAS is an acronym that helps remember the order of operations used in mathematics and programming (including Python). It stands for:
- P: Parentheses
- E: Exponents (Powers and Square Roots, etc.)
- MD: Multiplication and Division (from left to right)
- AS: Addition and Subtraction (from left to right)
Python follows this order of operations to evaluate expressions.
Parentheses (P)
Operations inside parentheses are evaluated first. This is true in Python as well.
result = (2 + 3) * 4 # Parentheses first, so it’s (5) * 4 = 20
Exponents (E)
Next, any exponentiation (powers) is calculated. In Python, you use ** for exponents.
result = 2 ** 3 # 2 raised to the power of 3 = 8
Multiplication and Division (MD)
Multiplication (*) and division (/) come next. In Python, multiplication and division are of equal precedence and are evaluated from left to right.
result = 6 / 2 * 3 # Left to right: (6 / 2) = 3, then 3 * 3 = 9
This means that even though division and multiplication have the same precedence, Python evaluates them from left to right, not from one to the other.
Addition and Subtraction (AS)
Finally, addition (+) and subtraction (-) are performed. These also have equal precedence, and like multiplication and division, they are evaluated from left to right.
result = 5 – 2 + 3 # Left to right: (5 – 2) = 3, then 3 + 3 = 6\
Example
Let’s consider the following example:
result = <span class="hljs-number">2</span> + <span class="hljs-number">3</span> * (<span class="hljs-number">4</span> ** <span class="hljs-number">2</span>) - <span class="hljs-number">6</span> / <span class="hljs-number">3</span>
Let’s break it down:
-
Parentheses first
4 ** 2
(4 squared) becomes 16.- Now the expression becomes:
2 + 3 * 16 - 6 / 3
.
-
Exponents are done, so we move on to multiplication and division (evaluated left to right):
3 * 16
= 48.6 / 3
= 2.0- Now the expression becomes:
2 + 48 - 2
.0
-
Addition and subtraction:
2 + 48
= 50.50 - 2.0
= 48.0