01.2 - Operators & Expressions
What is an Operator?
An operator is a symbol that tells Python to perform a specific operation on one or more operands.
result = 10 + 5 # `+` is the operator, 10 and 5 are operands
Python has 7 categories of operators:
1. Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | True division | 10 / 3 | 3.333... |
// | Floor division | 10 // 3 | 3 |
% | Modulo | 10 % 3 | 1 |
** | Exponentiation | 2 ** 8 | 256 |
# Division nuances
10 / 4 # 2.5 (always float)
10 // 4 # 2 (floor: rounds down)
-10 // 4 # -3 (floor of -2.5 is -3!)
10 % 4 # 2 (remainder)
# Common use of modulo
def is_even(n):
return n % 2 == 0
# String and list operators
"hello" + " world" # "hello world" (concatenation)
"ab" * 3 # "ababab" (repetition)
[1, 2] + [3, 4] # [1, 2, 3, 4]
2. Comparison Operators
Comparison operators return True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal | 5 == 5 | True |
!= | Not equal | 5 != 3 | True |
< | Less than | 3 < 5 | True |
> | Greater than | 5 > 3 | True |
<= | Less or equal | 5 <= 5 | True |
>= | Greater or equal | 6 >= 5 | True |
# Python allows chaining comparisons!
1 < 2 < 3 # True (equivalent to 1 < 2 and 2 < 3)
1 < 2 > 0 # True
10 <= 10 < 20 # True
# Warning: == vs is
a = [1, 2, 3]
b = [1, 2, 3]
a == b # True (same content)
a is b # False (different objects in memory)
x = None
x == None # True (works but not recommended)
x is None # True (preferred — checks identity)
3. Logical Operators
| Operator | Meaning | Example |
|---|---|---|
and | Both must be True | True and False → False |
or | At least one True | True or False → True |
not | Negation | not True → False |
age = 25
has_id = True
# Both conditions
if age >= 18 and has_id:
print("Access granted")
# Either condition
if age < 13 or age > 65:
print("Special pricing")
# Negation
if not has_id:
print("Show your ID")
Short-Circuit Evaluation
Python evaluates logical expressions lazily:
and: stops at firstFalseor: stops at firstTrue
# Short-circuit: safe division — division only evaluates if x != 0
x = 0
result = x != 0 and 10 / x # False — division never executed!
# Short-circuit with or: default value pattern
name = user_input or "Anonymous"
# If user_input is "" or None, name = "Anonymous"
4. Assignment Operators
| Operator | Example | Equivalent |
|---|---|---|
= | x = 5 | Assign 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 2 | x = x * 2 |
/= | x /= 2 | x = x / 2 |
//= | x //= 2 | x = x // 2 |
**= | x **= 2 | x = x ** 2 |
%= | x %= 3 | x = x % 3 |
score = 100
score += 10 # 110
score -= 5 # 105
score *= 2 # 210
# Walrus operator (Python 3.8+): assign and test simultaneously
import re
if match := re.search(r"\d+", "abc123"):
print(match.group()) # "123"
5. Identity Operators (is, is not)
| Operator | Meaning |
|---|---|
is | Same object in memory |
is not | Different objects in memory |
a = None
b = None
a is None # True (always use `is` with None)
a is not None # False
# Integer caching: Python caches small integers (-5 to 256)
x = 100
y = 100
x is y # True (cached)
x = 1000
y = 1000
x is y # False (not cached)
x == y # True (same value)
6. Membership Operators (in, not in)
| Operator | Meaning |
|---|---|
in | Element exists in a sequence |
not in | Element does not exist |
fruits = ["apple", "banana", "cherry"]
"banana" in fruits # True
"mango" not in fruits # True
# Works on strings
"py" in "python" # True
"z" not in "hello" # True
# Works on dicts (checks keys)
data = {"name": "Alice", "age": 30}
"name" in data # True
"email" in data # False
Operator Precedence (PEMDAS)
When multiple operators appear, Python follows this precedence (high to low):
| Priority | Operator | Description |
|---|---|---|
| 1 (highest) | () | Parentheses |
| 2 | ** | Exponentiation |
| 3 | +x, -x, ~x | Unary operators |
| 4 | *, /, //, % | Multiplication & division |
| 5 | +, - | Addition & subtraction |
| 6 | <<, >> | Bitwise shifts |
| 7 | & | Bitwise AND |
| 8 | ^ | Bitwise XOR |
| 9 | | | Bitwise OR |
| 10 | ==, !=, <, >, etc. | Comparisons |
| 11 | not | Logical NOT |
| 12 | and | Logical AND |
| 13 (lowest) | or | Logical OR |
# Without parentheses — can be confusing
2 + 3 * 4 # 14 (not 20! * before +)
2 ** 3 ** 2 # 512 (right-associative: 2 ** 9)
# With parentheses — always clear
(2 + 3) * 4 # 20
not True or True # True (not True = False, then False or True = True)
not (True or True) # False (True or True = True, then not True = False)
Rule: When in doubt, use parentheses. Clarity beats cleverness.
Key Vocabulary
| Term | Definition |
|---|---|
| Operator | A symbol performing an operation (+, ==, and) |
| Operand | The values on which an operator acts |
| Expression | Combination of values, variables, and operators that evaluates to a result |
| Floor division | // — divides and rounds down to nearest integer |
| Modulo | % — returns the remainder of a division |
| Short-circuit | Logical operators stop evaluating when the result is determined |
| Walrus operator | := — assigns and returns a value in one expression (Python 3.8+) |
| Operator precedence | Rules determining the order in which operators are evaluated |
Summary
- Python has 7 operator categories: arithmetic, comparison, logical, assignment, identity, membership, bitwise
/always returns float; use//for integer division- Use
is/is notfor identity checks (especiallyis None) - Use
in/not infor membership tests in lists, strings, dicts andandoruse short-circuit evaluation — useful for defaults and guards- When precedence is unclear, add parentheses to make intent explicit
📄️ 01.1 - Variables & Data Types
Master Python's built-in types: int, float, str, bool, None — and understand how variables work in a dynamically typed language
📄️ 01.2 - Operators & Expressions
Master Python's arithmetic, comparison, logical, bitwise, and assignment operators with operator precedence rules
📄️ 01.3 - Strings & I/O
Master Python string formatting (f-strings, format(), %), console I/O with input()/print(), and essential string operations
📄️ Lab - Module 01
Build an interactive command-line calculator using variables, operators, type conversion, and f-string formatting
📄️ Quiz - Module 01
30 interactive questions covering variables, data types, operators, and string formatting