Precedence, What Runs First

When operators from different families mix, precedence decides the order. The full pecking order, highest to lowest:

1. Parentheses ()

2. Exponent **

3. Multiply, divide, modulo * / % //

4. Add, subtract + -

5. Comparisons > < >= <= == !=

6. NOT

7. AND

8. OR

✦ The practical rule

Arithmetic happens before comparison, and comparison happens before logic. That's why age >= 18 and has_ticket works without parentheses, the comparison resolves to a Boolean first, then AND combines. When you're unsure, add parentheses. They cost nothing and they make intent obvious to the next reader, who is often you in six months.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Line 3 resolves in three stages: arithmetic (10-2=8), then two comparisons (8>3 is True, 5<8 is True), then AND. Add parentheses to line 1 so the addition happens first and it prints 16.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Write a check that lets someone in when they have a ticket AND are either a member OR over 65. Use parentheses so the or is grouped together, and try it with a few different values.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Truthiness, When Non-Booleans Act Like Booleans →
← Back