Operators and Conditionals
Compute, compare, combine conditions, and choose branches with clear Python logic.
Operators build expressions. Conditionals use the resulting values to choose which statements run.
Arithmetic operators
print(7 + 3) # 10
print(7 - 3) # 4
print(7 * 3) # 21
print(7 / 3) # 2.333... true division always returns float
print(7 // 3) # 2 floor division
print(7 % 3) # 1 remainder
print(7 ** 3) # 343 exponentiation// rounds down, not toward zero:
print(-7 // 3) # -3Use divmod when both quotient and remainder matter:
hours, minutes = divmod(135, 60)
print(hours, minutes) # 2 15Parentheses make precedence explicit:
average = (8 + 9 + 10) / 3Comparison and logical operators
Comparisons produce booleans:
age = 20
print(age >= 18) # True
print(age != 21) # True
print(18 <= age < 65) # True: chained comparisonCombine conditions with and, or, and not:
has_ticket = True
is_banned = False
may_enter = age >= 18 and has_ticket and not is_bannedPrecedence is not, then and, then or. Use parentheses when a reader could hesitate.
Membership
in and not in test membership:
role = "editor"
allowed_roles = {"editor", "admin"}
if role in allowed_roles:
print("Access granted")Membership in a dictionary checks keys, not values.
Truthiness
Conditions need not be literal booleans. These values are falsy:
FalseandNone- numeric zero, such as
0and0.0 - empty containers and text, such as
"",[],{}, andset()
Most other values are truthy:
name = ""
if name:
print(f"Hello, {name}")
else:
print("A name is required")Use explicit comparisons when zero and absence have different meanings:
discount = 0
if discount is None:
print("Discount not calculated")
else:
print(f"Discount: {discount}%")if, elif, and else
Only the first matching branch runs:
score = 84
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "Needs improvement"
print(grade) # BOrder matters. Put narrower or higher-priority conditions before broader ones.
Nested conditions are sometimes necessary, but combined conditions or early returns inside functions often read more clearly.
Conditional expressions
Use a conditional expression for one simple value choice:
status = "adult" if age >= 18 else "minor"Do not nest conditional expressions. A regular if statement is clearer when there are several
conditions or actions.
Short-circuit evaluation
and stops at the first falsy operand; or stops at the first truthy operand. This can safely
guard later work:
items = ["pen", "book"]
if items and items[0] == "pen":
print("The first item is a pen")The expression avoids indexing an empty list.
Logical operators return an operand, not necessarily True or False:
display_name = "" or "Anonymous"
print(display_name) # AnonymousUse this defaulting pattern only when every falsy value should trigger the default.
Assignment operators
count = 5
count += 2
count *= 3
print(count) # 21For mutable objects, augmented assignment may mutate in place. For immutable values, it binds a new object.
Common mistakes
- Writing
=instead of==in a comparison causesSyntaxError. - Using
&or|for boolean logic; those are bitwise operators. - Putting a broad condition before a narrower
elif, making the latter unreachable. - Writing
if x == "a" or "b":;"b"is always truthy. - Treating every falsy value as missing when
0or an empty collection is meaningful. - Comparing floats for exact equality after arithmetic.
Correct a multi-value comparison with membership:
if answer in {"yes", "y"}:
print("Confirmed")Decision guidance
- Use chained comparisons for ranges:
0 <= percentage <= 100. - Use a set for membership among several fixed choices.
- Use
if/eliffor mutually exclusive choices and separateifstatements for independent checks. - Use a conditional expression only when it improves a short assignment.
- Prefer explicit conditions when truthiness would hide an important distinction.
Practice
- Classify a temperature as freezing, cool, warm, or hot with ordered branches.
- Determine whether a year is a leap year: divisible by 4, except centuries unless divisible by 400.
- Convert total seconds to minutes and remaining seconds with
divmod. - Fix
if command == "start" or "run":and explain the bug.
LEARNING RECORD
Finish this lesson
Mark it complete when you can explain the main decision without looking.
KNOWLEDGE CHECK