Course contentsShow
← Python
Lesson 33 of 1,0601. Foundations and EnvironmentFree lesson

Managing Operator Precedence and Parentheses

Control the order of mathematical operations to ensure complex expressions evaluate correctly according to standard algebraic rules and Python syntax.

Mastering Operator Precedence and Parentheses

In this lesson, you will learn how to control the order in which Python performs calculations so that your programs always return the results you expect.

The Rule of Hierarchy

When you write an expression like result = 10 + 2 * 3, Python does not simply read from left to right. Instead, it follows a strict set of rules called operator precedence. Just like in standard algebra, multiplication and division are performed before addition and subtraction.

In the example above, Python calculates 2 * 3 first (getting 6), and then adds 10, resulting in 16. If you were hoping for the answer to be 36—by adding 10 and 2 first—you need a way to override this behavior.

Controlling Order with Parentheses

The most powerful tool in your belt for managing order is the parenthesis (). Python is programmed to evaluate whatever is inside parentheses first, regardless of the default precedence rules. By wrapping 10 + 2 in parentheses, you force Python to handle that part of the expression before multiplying:

# Without parentheses
print(10 + 2 * 3)   # Output: 16

# With parentheses
print((10 + 2) * 3) # Output: 36

Why This Matters

As your programs grow, you will often deal with complex formulas—like calculating the average of variables or adjusting values based on user input. If you rely solely on default order, you might introduce "logic errors" where the code runs without crashing, but the math is fundamentally wrong.

Using parentheses makes your code more readable, too. Even if you know the order of operations by heart, someone reading your code might not. Adding parentheses clearly signals your intent, showing exactly which parts of the calculation should happen first. When in doubt, adding parentheses to clarify your logic is always a great practice.

Key Takeaway: Python follows standard algebraic precedence, but you can override it at any time by wrapping specific parts of your expression in parentheses to ensure they are calculated first.