Lecture

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:

  1. Parentheses ()

  2. Exponentiation **

  3. Multiplication *, Division /, Modulo %, Floor Division //

  4. Addition +, Subtraction -

Let us explore how operator precedence is applied using an example.

Basic Rules of Operator Precedence
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.

Example of Controlling Precedence
result_with_parentheses = (10 + 2) * (3 ** 2) / 4 print(result_with_parentheses) # 36.0
Mission
0 / 1

Which of the following has the highest operator precedence in Python?

Addition +

Multiplication *

Exponentiation **

Modulus %

Lecture

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result