Advanced Conditionals

Python Control FlowFree Lesson

Advertisement

Advanced Conditionals

Ternary operators, match-case, chained comparisons, and conditional patterns.

Overview

Master advanced conditional patterns.

Ternary Operator

# Basic syntax
x = 10
result = "positive" if x > 0 else "non-positive"
print(result)  # positive

# Nested ternary
x = 15
result = "positive" if x > 0 else "zero" if x == 0 else "negative"
print(result)  # positive

# In function calls
def greet(name):
    return f"Hello, {'friend' if not name else name}!"

print(greet(""))      # Hello, friend!
print(greet("Alice")) # Hello, Alice!

Chained Comparisons

x = 15

# Multiple conditions
if 10 < x < 20:
    print("x is between 10 and 20")

# Equivalent to
if 10 < x and x < 20:
    print("x is between 10 and 20")

# Range check
age = 25
if 18 <= age <= 65:
    print("Working age")

# Multiple equality
a = b = c = 5
if a == b == c:
    print("All equal")

Match-Case (Python 3.10+)

# Basic match
def get_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:
            return "Unknown"

print(get_status(200))  # OK

# Pattern matching with OR
match command:
    case "quit" | "exit" | "q":
        print("Exiting...")
    case "help" | "h":
        print("Showing help...")
    case _:
        print("Unknown command")

# Matching with capture
match point:
    case (0, 0):
        print("Origin")
    case (x, 0):
        print(f"On x-axis at {x}")
    case (0, y):
        print(f"On y-axis at {y}")
    case (x, y):
        print(f"Point at ({x}, {y})")

# Class matching
match event:
    case Click(position=(x, y)):
        handle_click(x, y)
    case KeyPress(key_name="Q"):
        quit()
    case KeyPress(key_name=key):
        handle_key(key)

Conditional Patterns

# Guard clauses
def process_data(data):
    if not data:
        return None
    if not isinstance(data, list):
        return None
    if len(data) == 0:
        return None
    
    return [x * 2 for x in data]

# Dictionary dispatch
def handle_action(action, value):
    actions = {
        "add": lambda x: x + 1,
        "subtract": lambda x: x - 1,
        "multiply": lambda x: x * 2,
    }
    
    handler = actions.get(action)
    if handler:
        return handler(value)
    return None

Practice

Implement a calculator using match-case.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement