Python Syntax Wrap-Up Problems — Combine Control Flow, Functions, and Exceptions
Three Python syntax wrap-up problems: a filter-and-square list comprehension, a safe_divide using try / except, and a @double decorator that doubles the return value.
Problem 1: Filter and transform with a comprehension
Combine an if filter inside a list comprehension with the ` power operator. Pick out only the elements that match a condition and turn them into something new** — that's the bread-and-butter use of comprehensions.
Problem 2: Build a safe division function with try / except
Write safe_divide(a, b) so it doesn't crash on a zero divisor. This pulls together def for defining a function, try / except for catching an exception, and using return to send back different values depending on what happened.
try. On error, control jumps to the matching except block.Problem 3: Modify a function's return value with a decorator
Build a decorator @double that doubles whatever the wrapped function returns — without touching the function's body. This forces you to write the decorator pattern itself: a function that takes a function and returns a new function.
@double is the same as add = double(add).Nice work getting through this
That wraps up Python Syntax. You've covered control flow with conditionals, loops, and exceptions, function definitions with def / lambda, comprehensions, higher-order functions, decorators, and generators — pretty much every tool you need to drive a program. You can now write functions that take some values, transform them, and return a result on your own.
The next chapter, Python Object-Oriented Programming, is about defining your own types: writing class, setting up constructors with __init__, inheritance, polymorphism, encapsulation, special methods like __add__, context managers with with, and type hints. It's how you bundle data and behavior together into one design.