Python Conditional Statements (if, elif, else)

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 7 of 65 ๐Ÿ“‚ Phase 2: Operators & Control Flow ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: if-elif-else ยท Guard Clauses ยท Ternary Operator ยท match-case
Master decision making and control flow branching in Python: if conditions, elif ladders, else fallbacks, guard clauses, ternary expressions, and match-case.
1Decision Making Architecture & The if-elif-else Ladder

Conditional statements branch execution dynamically. The conditions are evaluated sequentially from top to bottom; once the first True condition executes, all subsequent elif and else branches are skipped:

๐Ÿ’ป Example 1: if-elif-else Grade Calculator
# Grading system based on marks:
marks = 82

if marks >= 90:
    print("Grade: A+ (Outstanding!) ๐ŸŒŸ")
elif marks >= 75:
    print("Grade: A (Very Good!) โœจ")
elif marks >= 50:
    print("Grade: B (Pass) ๐Ÿ‘")
else:
    print("Grade: Fail โŒ")
๐Ÿ” Step-by-Step Execution:
  • Python tests marks >= 90 (82 >= 90 is False) -> skips.
  • Python tests marks >= 75 (82 >= 75 is True) -> prints Grade: A (Very Good!) โœจ.
  • All remaining branches (elif marks >= 50 and else) are immediately bypassed!
2Flattening Code with Guard Clauses (Avoiding Pyramid of Doom)

Deeply nested if statements make code difficult to read. Professional developers use Guard Clauses (early returns) to keep logic flat and clean:

๐Ÿ’ป Example 2: Guard Clauses (Early Returns)
def check_user_access(is_logged_in, has_permission, is_banned):
    # Guard Clauses (Early Exits):
    if not is_logged_in:
        return "Please log in first."
    if is_banned:
        return "Account is banned!"
    if not has_permission:
        return "Access denied."
        
    return "Welcome to Admin Dashboard! โœ…"

print(check_user_access(True, True, False))
๐Ÿ” Code Quality Insight:

Guard clauses handle failure/invalid conditions early and return immediately, keeping the "happy path" un-indented and crystal clear.

3Ternary Operator (Inline One-Line if-else)

Python provides an inline ternary conditional expression with the syntax: value_if_true if condition else value_if_false:

๐Ÿ’ป Example 3: Ternary Conditional Expression
age = 20
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)

# Dynamic fee calculation:
is_weekend = True
entry_fee = 25 if is_weekend else 15
print(f"Entry Fee: ${entry_fee}")
๐Ÿ” One-line Syntax:

Ternary expressions are perfect for simple variable assignments based on a single condition.

4Structural Pattern Matching: match-case (Python 3.10+)

Python 3.10 introduced match-case, replacing clumsy switch-case statements with powerful structural pattern matching and OR patterns (|):

๐Ÿ’ป Example 4: match-case Pattern Matching
http_status = 404

match http_status:
    case 200:
        print("200 OK: Request succeeded! โœ…")
    case 401 | 403:
        print("Auth Error: Access forbidden.")
    case 404:
        print("404 Not Found: Page does not exist! โŒ")
    case _:
        print("Other Server Status Code")
๐Ÿ” match-case Features:
  • case 401 | 403: matches either 401 OR 403.
  • case _: acts as the wildcard fallback (equivalent to default: in C/Java).
โš ๏ธ Common Developer Pitfall: Using Multiple Separate "if" Statements Instead of "elif"

If you use multiple if statements sequentially, Python evaluates EVERY single condition independently, even after finding a match. Using elif ensures that once the first True branch executes, all subsequent checks are skipped.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Check if a year is a Leap Year (divisible by 4 and not divisible by 100, or divisible by 400).

Python 3 Practice Challenge โ–ถ Run in Compiler
year = 2024

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"โœ… {year} is a Leap Year!")
else:
    print(f"โŒ {year} is NOT a Leap Year.")
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

Q Does Python have a traditional switch-case statement?

Python 3.10 introduced match-case (Structural Pattern Matching) which replaces switch-case and supports deep object destructuring and guard conditions.

Q What is the difference between pass and continue?

pass is a no-op placeholder that allows execution to proceed to the next line. continue is used exclusively inside loops to skip the remainder of the current loop iteration and jump to the next cycle.

Q Can ternary operators be chained in Python?

Yes: x = "A" if score >= 90 else ("B" if score >= 80 else "C"). However, if chaining exceeds two levels, use standard if-elif-else for better readability.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026