liveBook · Manning

Operator precedence

As explained in Get Programming: Learn to code with Python

Operator precedence is the set of rules that determines the order in which operators and their operands are evaluated in an expression.

Operator precedence determines the order in which parts of an expression are evaluated. In Python, it matters when a conditional combines arithmetic, comparisons, membership checks, and Boolean operators such as and and or. section 14.1

A condition that looks similar but behaves differently

Correct: if num_a < 0 and num_b < 0: print("both negative")\nIncorrect: if num_a and num_b < 0: print("both negative")\n\nThe first condition checks whether both values are less than zero. The second does not repeat the comparison for num_a, so it can print "both negative" when num_a is 1 and num_b is -1. Quick checks include 3 < 2 ** 3 and 3 == 3, and expressions combining or, and, membership, and len(). section 14.1

When an expression feels unclear, add parentheses, work through each operation in order, and test the result instead of relying on appearance alone. section 14.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines a complete precedence order, explains left-to-right ties, and stops short of deeper expression internals.
Examples
Uses negative-number conditions, precedence quick checks, truth tables, and console outputs from an incorrect condition.
What it assumes
Assumes basic expressions and arithmetic precedence while teaching additional comparison and logical precedence rules.
What you can do after
Diagnose misleading compound conditions and evaluate Python expressions in precedence order.
How it connects
Connects expressions with arithmetic operators, comparison operators, Boolean operators, membership, identity, and conditional statements.

Also explained in

Compare how 7 books explain operator precedence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.