Determining Operator Precedence
Just like in mathematics, where multiplication is performed before addition, the same concept of precedence
applies to operators in programming.
In this lesson, we will explore the precedence of numeric operators in greater depth.
Basic Rules of Operator Precedence
In Python, operator precedence is applied in the following order:
-
Parentheses
()
-
Exponentiation
**
-
Multiplication
*
, Division/
, Modulo%
, Floor Division//
-
Addition
+
, Subtraction-
Let us explore how operator precedence is applied using an example.
result = (10 + 2) * 3 ** 2 / 4
print(result) # 27.0
In the above example, (10 + 2)
is calculated first, resulting in 12
, then 3 ** 2
is calculated, resulting in 9
.
Next, 12 * 9
is calculated, resulting in 108
, and finally 108 / 4
is calculated, resulting in 27
.
Parentheses can be used to control the order of evaluation. Operations inside parentheses are performed first.
result_with_parentheses = (10 + 2) * (3 ** 2) / 4
print(result_with_parentheses) # 36.0
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.