📘 Lesson 08 · Intermediate

Python Conditionals

Master if, elif, else, nested conditions, and ternary expressions with examples and output.

How Conditionals Work

Conditionals let your program make decisions — running different code depending on whether a condition is True or False. Python checks each if/elif condition from top to bottom and runs only the first matching block. Once a block runs, all remaining branches are skipped — even if multiple conditions are True.

if / elif / else

grade.py
score = 75

if score >= 90:
    print("Grade: A — Excellent!")
elif score >= 80:
    print("Grade: B — Good")
elif score >= 70:
    print("Grade: C — Satisfactory")
else:
    print("Grade: F — Failed")
▶ Output
Grade: C — Satisfactory

With score = 75, Python checks 75 >= 90 (False), then 75 >= 80 (False), then 75 >= 70 (True) — runs that block and stops. The else clause at the end is a catch-all that only runs if no condition above matched.

Combining Conditions

Use and, or, and not to combine multiple checks in one expression. The in keyword tests membership in a list or string — it is much cleaner than writing multiple or comparisons.

combined.py
age = 22
has_id = True

if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")

# "in" is cleaner than multiple "or" checks
colour = "red"
if colour in ["red", "green", "blue"]:
    print(f"{colour} is a primary colour")
▶ Output
Entry allowed
red is a primary colour

Ternary Expression

Python's ternary expression writes a simple if/else on a single line: value_if_true if condition else value_if_false. Use it for simple variable assignments — it avoids 4 lines when 1 will do. For complex logic, stick to a regular if/else for clarity.

ternary.py
age = 20
status = "adult" if age >= 18 else "minor"
print(status)

x = 7
print(f"{x} is {"even" if x % 2 == 0 else "odd"}")
▶ Output
adult
7 is odd

Nested if

You can place an if inside another if to check a second condition only when the first is True. Keep nesting shallow — more than 2–3 levels deep is hard to follow.

nested.py
temp = 35
if temp > 30:
    print("Hot outside")
    if temp > 40:
        print("Extreme heat warning!")
    else:
        print("Stay hydrated")
else:
    print("Comfortable")
▶ Output
Hot outside
Stay hydrated
Flatten nested conditions where possible using and/or. Deep nesting is a code smell — it usually means the logic should be reorganised.

🧠 Quick Check

What keyword handles additional conditions after if?

else
then
elif
when

Tags

ifelseelifconditionalsternarynested ifboolean logic