Learn Python
>>> operators.op_precedence

Operator Precedence in Python

#concept

When an expression mixes several operators, precedence determines which ones run first — the same idea as "multiplication before addition" from ordinary math, extended to every operator Python has. Parentheses always override precedence and are the clearest way to force a specific order, both for Python and for whoever reads the code next.

#how it works
1

Parentheses run first, always

Use them to force a specific order, or simply to make intent obvious.

2

Exponentiation runs next

** outranks every other arithmetic operator.

3

Multiplication-tier before addition-tier

*, /, //, and % all run before + and -.

4

Comparisons run after arithmetic

==, <, >, and similar operators are evaluated once the arithmetic on either side is resolved.

5

Logical operators run last

In the order not, then and, then or.

#example
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 2 ** 2)
print(True or False and False)
Output
14
20
6
True
12 + 3 * 4 computes 3 * 4 first (12), then adds 2, giving 14 — multiplication runs before addition.
2(2 + 3) * 4 forces the addition first with parentheses, giving 5 * 4 = 20.
310 - 2 ** 2 computes 2 ** 2 first (4), then subtracts from 10, giving 6 — exponentiation outranks subtraction.
4True or False and False computes and first (False and False is False), then or (True or False is True) — and outranks or.
#use cases
Avoiding subtle bugs in calculations, like forgetting that ** outranks a leading minus sign in -2 ** 2 (which is -4, not 4)
Writing conditions that combine and / or correctly once more than two conditions are involved
Using parentheses defensively in any expression complex enough that a future reader might guess the order wrong
Debugging an unexpected result by manually checking which operator actually ran first

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.