Operator Precedence in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will gain a practical understanding of operator precedence in Python. Just like in mathematics, Python follows specific rules to determine the order in which operations are performed within an expression. A solid grasp of these rules is essential for writing code that is both correct and predictable.

We will start by exploring the precedence of basic arithmetic operators. Then, we will see how higher-level operators like exponentiation and comparison fit into the hierarchy. Finally, you will learn how to use parentheses to override the default order of operations, a technique that is crucial for both controlling calculations and improving code readability.

Basic Arithmetic Precedence

In Python, as in standard mathematics, some arithmetic operators have a higher precedence than others. Specifically, multiplication (*) and division (/) are performed before addition (+) and subtraction (-). When operators have the same precedence, they are evaluated from left to right.

Let's observe this behavior. The setup process has already created a file for you. In the WebIDE file explorer on the left, find and open the file named operator_precedence.py located in the ~/project directory.

Add the following code to the file:

## Multiplication and division are evaluated before addition and subtraction.
result = 10 + 4 * 3 - 10 / 5
print(result)

This expression contains addition, multiplication, subtraction, and division. Let's predict the order of operations:

  1. Python will first perform the multiplication: 4 * 3 equals 12.
  2. Next, it will perform the division: 10 / 5 equals 2.0. Note that standard division in Python 3 always results in a floating-point number.
  3. The expression is now 10 + 12 - 2.0.
  4. Finally, it will perform the addition and subtraction from left to right: 10 + 12 is 22, and 22 - 2.0 is 20.0.

Save the file by pressing Ctrl + S. To run the code, open a terminal in the WebIDE (Terminal -> New Terminal) and execute the following command:

python ~/project/operator_precedence.py

You will see the calculated result printed to the terminal.

20.0

The output matches our prediction, confirming the precedence of multiplication and division over addition and subtraction.

Higher-Level Operators

Python's operator hierarchy extends beyond basic arithmetic. The exponentiation operator (**) has a higher precedence than multiplication and division. Furthermore, all arithmetic operators have a higher precedence than comparison operators like "greater than" (>).

Let's add more examples to our script to see this in action. Modify the ~/project/operator_precedence.py file to include two new expressions:

## Multiplication and division are evaluated before addition and subtraction.
result = 10 + 4 * 3 - 10 / 5
print(result)

## Exponentiation has higher precedence than multiplication.
exp_result = 2 * 3 ** 2
print(exp_result)

## Arithmetic operators have higher precedence than comparison operators.
comp_result = 18 > 5 + 10
print(comp_result)

Let's analyze the new lines:

  1. In 2 * 3 ** 2, the exponentiation 3 ** 2 is calculated first, resulting in 9. Then, the multiplication 2 * 9 is performed, giving 18.
  2. In 18 > 5 + 10, the addition 5 + 10 is calculated first, resulting in 15. Then, the comparison 18 > 15 is evaluated, which is True.

Save the file (Ctrl + S) and run the script again.

python ~/project/operator_precedence.py

The terminal will now display the results of all three expressions.

20.0
18
True

This confirms that Python evaluates exponentiation first, followed by other arithmetic operations, and finally, comparison operations.

Using Parentheses to Control Evaluation Order

While Python's precedence rules are consistent, complex expressions can be difficult to read. To override the default order or to simply make your intentions clear, you can use parentheses (). Any expression enclosed in parentheses is evaluated first.

Let's modify one of our previous examples to see the effect of parentheses. Add a new expression to the end of ~/project/operator_precedence.py.

## Multiplication and division are evaluated before addition and subtraction.
result = 10 + 4 * 3 - 10 / 5
print(result)

## Exponentiation has higher precedence than multiplication.
exp_result = 2 * 3 ** 2
print(exp_result)

## Arithmetic operators have higher precedence than comparison operators.
comp_result = 18 > 5 + 10
print(comp_result)

## Using parentheses to change the order of evaluation.
forced_result = (10 + 4) * 3
print(forced_result)

Let's analyze the new line (10 + 4) * 3:

  1. Because 10 + 4 is inside parentheses, it is evaluated first, resulting in 14.
  2. Then, the multiplication 14 * 3 is performed, giving 42.

This is different from 10 + 4 * 3, which we know evaluates to 22. The parentheses completely changed the outcome.

Save the file and run the script one last time.

python ~/project/operator_precedence.py

The output will now include the result of our parenthesized expression.

20.0
18
True
42

Using parentheses, even when not strictly necessary, is a good practice. It makes the order of operations explicit, which improves code readability and reduces the chance of bugs caused by precedence misunderstandings.

Summary

In this lab, you have explored the fundamental concept of operator precedence in Python. You started with basic arithmetic, confirming that multiplication and division are prioritized over addition and subtraction. You then learned that other operators, like exponentiation and comparison, have their own place in the hierarchy.

Most importantly, you practiced using parentheses to explicitly control the order of evaluation. This skill is vital for writing code that is not only functionally correct but also clear and easy for others to understand. By mastering operator precedence, you have taken a significant step toward writing more robust and reliable Python programs.