In this lesson, you’ll learn how to combine values into expressions using Python’s operators. We’ll cover arithmetic, comparison, logical, assignment, membership, and identity operators, with clear, practical examples.
1) Expressions & Precedence (Quick Intro)
An expression is any piece of code that produces a value. Python evaluates operators by precedence (order of operations). Use parentheses (...) to make your intent clear.
result = 2 + 3 * 4 # 2 + (3*4) = 14
result = (2 + 3) * 4 # (2+3)*4 = 20
2) Arithmetic Operators
Basic math with numbers:
a = 10
b = 3
print(a + b) # 13 (addition)
print(a - b) # 7 (subtraction)
print(a * b) # 30 (multiplication)
print(a / b) # 3.333... (true division, always float)
print(a // b) # 3 (floor division, drops fractional part)
print(a % b) # 1 (modulo / remainder)
print(a ** b) # 1000 (exponent / power)
Tips:
/is always floating-point division. Use//when you want an integer result.- Use parentheses to make complex calculations readable.
3) Comparison Operators
Comparisons evaluate to True or False:
x = 7
print(x == 7) # True (equal)
print(x != 7) # False (not equal)
print(x < 10) # True (less than)
print(x > 10) # False (greater than)
print(x <= 7) # True (less or equal)
print(x >= 8) # False (greater or equal)
Chaining Comparisons (Pythonic)
age = 18
print(16 <= age < 21) # True (checks both in one go)
4) Logical Operators
Combine boolean expressions with and, or, and not. Python evaluates them left to right and uses short-circuit rules (it skips the right side if the left side already decides the result).
Basics
temp = 28
is_raining = False
if temp > 25 and not is_raining:
print("Great day for a walk!") # True AND True → runs
Short-circuit examples
A) Guard pattern with and (avoids errors)
# Short-circuit with AND: second part isn't evaluated if the first is False
items = [] # try changing to ["apple"] to see difference
# If items is empty (falsy), Python won't evaluate items[0] — avoids IndexError
if items and items[0] == "apple":
print("First item is apple")
else:
print("No first item or not apple")
B) Default/fallback with or
provided_name = "" # try "", None, or "Ammar"
# x or y returns the first truthy value → great for defaults
name = provided_name or "Guest"
print(name) # "Guest" when provided_name is "" or None; otherwise the real name
Why it works: empty string "", None, 0, empty lists/dicts are falsy; non-empty strings/numbers are truthy.
Same fallback using if/else (for clarity)
if provided_name:
name = provided_name
else:
name = "Guest"
⚠️ Caution: If 0 or "" are valid values you want to keep, or will replace them (because they’re falsy). In that case, check only for None:
provided = "" # keep empty string as-is
name = provided if provided is not None else "Guest"
5) Assignment Operators
Assign values to names, and use augmented assignment to update in place.
x = 10 # simple assignment
x += 5 # x = x + 5 → 15
x -= 2 # x = x - 2 → 13
x *= 3 # x = x * 3 → 39
x /= 4 # x = x / 4 → 9.75
x //= 2 # x = floor(x / 2) → 4.0
x %= 3 # x = x % 3 → 1.0
x **= 2 # x = x ** 2 → 1.0
Multiple Assignment & Unpacking (Pythonic)
# Multiple variables in one line
name, age = "Ammar", 25
# Swap without a temp variable
a, b = 1, 2
a, b = b, a # a=2, b=1
# Unpack lists/tuples
x, y, z = [10, 20, 30]
Optional: Walrus Operator := (Python 3.8+)
Assign and use a value in one expression:
# Read and test in the same expression
while (line := input("Value (blank to stop): ").strip()):
print("You entered:", line)
6) Membership Operators
Check whether a value is contained in a sequence or mapping.
print("py" in "python") # True (substring)
print(3 in [1, 2, 3, 4]) # True (list)
print("id" in {"id": 1, "name": "Ali"}) # True (dict checks KEYS)
print("Ali" in {"id": 1, "name": "Ali"}.values()) # True (values)
print(5 not in (1, 2, 3)) # True
Note: in on a dict checks keys by default. Use mydict.values() or mydict.items() to search values or key/value pairs.
7) Identity Operators
Identity checks whether two names refer to the same object in memory, not just equal values.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same values)
print(a is b) # False (different objects)
print(a is c) # True (same object)
# Best practice: compare to None using 'is'
x = None
if x is None:
print("x is not set yet")
Rule of thumb: Use == for value comparison. Use is only for identity checks (e.g., with None or singletons).
Operator Precedence (Handy Mini List)
From higher to lower (simplified selection):
(...)(parentheses)**- unary
+-not *///%+-- comparisons
<<=>>===!=isin andor
When in doubt, add parentheses for clarity.
Key Takeaways
- Arithmetic:
+-*///%**— use//for floor division. - Comparisons return booleans; you can chain them (e.g.,
0 < x < 10). - Logical:
and,or,not— short-circuit behavior can skip work. - Assignment: simple
=and augmented forms like+=, plus multiple assignment/unpacking. - Membership:
in/not inchecks sequences; on dicts it checks keys. - Identity:
is/is notchecks object identity; useis Nonefor None checks. - Precedence matters — use parentheses for readability and correctness.
Next up: Control Flow — conditions, loops, and loop controls.
Previous: Python Basics
Leave a comment
Your email address will not be published. Required fields are marked *
