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 delve deeper into the precedence of numeric operators.
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's explore how operator precedence is applied through 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
Which of the following has the highest operator precedence in Python?
Addition +
Multiplication *
Exponentiation **
Modulus %
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result