Lesson 4: Operators & Expressions
Arithmetic, comparison, logical, and assignment operators — plus expression evaluation order.
What are Operators?
Operators are the verbs of programming — they tell Python what to do with values. You already use them in math class; Python just gives them superpowers like integer division and modulo. An expression is any combination of values and operators that Python can evaluate to a single result.
What You'll Learn in This Lesson
- Use arithmetic, comparison, and logical operators
- Understand operator precedence (order of operations)
- Use assignment shortcuts like
+= - Split numbers into digits with
//and% - Understand the difference between
=and==
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 7 + 3 |
10 |
- |
Subtraction | 7 - 3 |
4 |
* |
Multiplication | 7 * 3 |
21 |
/ |
Division (always float) | 7 / 2 |
3.5 |
// |
Floor division (integer) | 7 // 2 |
3 |
% |
Modulo (remainder) | 7 % 2 |
1 |
** |
Power | 2 ** 3 |
8 |
Two operators deserve special attention:
//floor division drops the decimal part:17 // 5is3(not 3.4).%modulo returns the remainder:17 % 5is2, because17 = 3*5 + 2.
Pizza visualization for modulo: 17 slices ÷ 5 friends = 3 full slices each, and 2 slices left over. The
//gives you 3, the%gives you 2.
+ and * also work on other types:
print("Py" + "thon") # 'Python' — concatenation
print("ha" * 3) # 'hahaha' — repetition
print([1, 2] + [3, 4]) # [1, 2, 3, 4] — list concatenation (Lesson 8)
This is called operator overloading — the same symbol means different things depending on the type. It is convenient but a common source of surprises: "5" + 5 raises TypeError because a string and an int don't mix.
Comparison Operators
Comparisons always return a boolean — True or False:
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | 5 == 5 → True |
!= |
Not equal | 5 != 4 → True |
> |
Greater than | 5 > 4 → True |
< |
Less than | 5 < 4 → False |
>= |
Greater or equal | 5 >= 5 → True |
<= |
Less or equal | 4 <= 5 → True |
Never confuse = (assignment) with == (comparison). A single = stores a value; a double == asks a question.
Comparisons chain naturally in Python:
age = 25
print(18 <= age < 60) # True — chained comparison, one expression
That single line is equivalent to 18 <= age and age < 60 — Python lets you write the math-style version directly.
Logical Operators
Logical operators combine booleans:
| Operator | Rule | Example |
|---|---|---|
and |
Both sides True | True and False → False |
or |
At least one side True | True or False → True |
not |
Flips True ↔ False | not True → False |
| A | B | A and B |
A or B |
not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
These let you write real-world rules: "Can enter if age ≥ 18 and has ID".
Short-circuiting is a powerful side effect: Python evaluates and/or left to right and stops as soon as the answer is decided. In a and b, if a is falsy, b never runs. In a or b, if a is truthy, b never runs. This is used to write safe one-liners:
# Only divide if denominator is non-zero
result = x / y if y != 0 else 0
Precedence — Order of Operations
Python follows standard math rules. From highest to lowest priority:
- Parentheses
( ) - Exponents
** *,/,//,%(left to right)+,-(left to right)- Comparisons (
==,>, ...) not, thenand, thenor- Assignment
=
print(3 + 4 * 2) # 11 (multiplication first)
print((3 + 4) * 2) # 14 (parentheses override)
print(2 ** 3 ** 2) # 512 — ** binds right-to-left: 2 ** (3 ** 2)
Rule of thumb: when in doubt, add parentheses. Clarity beats cleverness every time.
Assignment Shortcuts
x += 5 is shorthand for x = x + 5. The shortcut works with most operators:
| Shortcut | Equivalent |
|---|---|
x += 5 |
x = x + 5 |
x -= 5 |
x = x - 5 |
x *= 5 |
x = x * 5 |
x /= 5 |
x = x / 5 |
x //= 5 |
x = x // 5 |
x %= 5 |
x = x % 5 |
x **= 2 |
x = x ** 2 |
These keep counters, totals, and accumulators compact — you will use += on almost every loop you write.
Real-World Uses of // and %
- Time math:
total_minutes = 130→hours = 130 // 60(2),mins = 130 % 60(10). - Even/odd checks:
n % 2 == 0means even. - Splitting digits:
123 % 10→3;123 // 10→12. - Cycling/wrapping:
index % len(items)wraps an index around a list forever. - Coin/cash change: divide by the largest denomination with
//, keep the remainder with%.
Common Mistakes to Avoid
- Mistake: Using
=inside anifcondition — Fix: always use==for comparison. - Mistake: Expecting
7 / 2to give3— Fix:/always gives a float (3.5); use//for integer division. - Mistake: Forgetting that
andbinds tighter thanor— Fix: add parentheses to make the logic explicit. - Mistake:
"5" + 5— Fix: cast first:int("5") + 5. - Mistake: Assuming
**binds left-to-right — Fix: it binds right-to-left:2 ** 3 ** 2is512. - Mistake: Using
%when you want/on negative numbers — Fix:-7 % 3is2in Python (not-1); remember modulo results share the sign of the divisor.
Professional Tips & Tricks
- Never use
=inside conditions — that is assignment. Use==for comparison. - Wrap long boolean conditions in parentheses for readability.
- Use
//and%together to split numbers into digits, coins, or time units. - Leverage chained comparisons:
18 <= age < 60is clearer than two separate checks. - Use
+=for accumulators inside loops.
Key Takeaways
- Arithmetic:
/always floats;//floors;%gives the remainder. - Comparisons return
True/False;==compares,=assigns. and/or/notcombine booleans;and/orshort-circuit.- Parentheses control precedence — use them liberally.
+=,-=,*=are assignment shortcuts.//and%are the real-world workhorses for time, digits, and wrapping.
Next up: Control flow — conditionals and loops that make decisions.
# Operators in action
a, b = 17, 5
print("Addition:", a + b)
print("Division:", a / b) # float division
print("Floor div:", a // b) # drops the remainder
print("Modulo:", a % b) # remainder (17 = 3*5 + 2)
# Comparison + logical operators
score = 85
passed = score >= 40
distinction = score >= 75
print("Passed:", passed)
print("Distinction:", distinction)
print("Passed AND distinction:", passed and distinction)
print("NOT failed:", not (score < 40))
# Precedence: parentheses rule!
print("3 + 4 * 2 =", 3 + 4 * 2) # 11, not 14
print("(3 + 4) * 2 =", (3 + 4) * 2) # 14
# Assignment shortcuts
total = 10
total += 5 # total = 15
total *= 2 # total = 30
print("Total after shortcuts:", total)Lesson Code (Python)
# Operators in action
a, b = 17, 5
print("Addition:", a + b)
print("Division:", a / b) # float division
print("Floor div:", a // b) # drops the remainder
print("Modulo:", a % b) # remainder (17 = 3*5 + 2)
# Comparison + logical operators
score = 85
passed = score >= 40
distinction = score >= 75
print("Passed:", passed)
print("Distinction:", distinction)
print("Passed AND distinction:", passed and distinction)
print("NOT failed:", not (score < 40))
# Precedence: parentheses rule!
print("3 + 4 * 2 =", 3 + 4 * 2) # 11, not 14
print("(3 + 4) * 2 =", (3 + 4) * 2) # 14
# Assignment shortcuts
total = 10
total += 5 # total = 15
total *= 2 # total = 30
print("Total after shortcuts:", total)Console Output
Addition: 22
Division: 3.4
Floor div: 3
Modulo: 2
Passed: True
Distinction: True
Passed AND distinction: True
NOT failed: True
3 + 4 * 2 = 11
(3 + 4) * 2 = 14
Total after shortcuts: 30Code Visualization Tips
- Make a trace table: write each variable, update its value row by row as you read the code.
- Say 'evaluate the right side first' out loud for every assignment — that is how Python thinks.
- Visualize modulo as a pizza: 17 slices ÷ 5 friends = 3 full slices each, 2 slices left over.
Professional Tips & Tricks
- Never use = inside conditions — that is assignment. Use == for comparison.
- Wrap long boolean conditions in parentheses for readability.
- Use // and % together to split numbers into digits, coins, or time units.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Problem 1: Power Multiplier 1
Test Your Knowledge
Instant feedbackQuick Check: Lesson 4: Operators & Expressions
Up next · Continue learning
Conditional Branches & Loops
Evaluating truth tables, if/elif/else routing, for and while loops, break, and continue.