Python 101Free
FOUNDATIONS

Operators and Expressions

Arithmetic, comparison, and logical operators, plus how they combine.

SECTION 01

The operator table

Operators in Python fall into three families. Arithmetic operators (+, -, *, /, //, %, **) work on numbers. Comparison operators (==, !=, <, >, <=, >=) compare two values and return a bool. Logical operators (and, or, not) combine booleans.

Python has the standard precedence rules. Multiplication binds tighter than addition, comparison binds tighter than logical. The actual rules are not the kind of thing you should memorize. When precedence matters, add parentheses, the reader will thank you.

A few operators do double duty. + adds numbers and concatenates strings. * multiplies numbers and repeats sequences. in checks containment for any iterable. The shared symbols are part of why Python code reads naturally for different kinds of values.

SECTION 02

Truthiness and short-circuit

In Python, every value can be used in a boolean context. The empty string, the empty list, zero, and None count as false. Everything else counts as true. This is what people mean by truthiness.

The and and or operators do not return a strict True or False. They short-circuit and return whichever operand decided the result. 0 and x returns 0 without ever evaluating x. 42 or x returns 42 for the same reason.

This is occasionally useful (default values via or, guarded calls via and) and occasionally a pitfall (a 0 that you wanted to keep getting replaced by a fallback). Knowing the rule lets you read existing code instead of guessing.

python
bool([])              # False
bool("hi")            # True

0 or "fallback"       # 'fallback'
42 or "fallback"      # 42  (short-circuits, never reads the right side)
user and user.name    # None if user is None, else user.name
← PREVIOUS
Variables and Types
NEXT →
Strings