Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
How to Return Success or Error as a Tuple in Python (Result Type Pattern)
Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
"""Return (True, result) on success, (False, error_message) on failure."""
if divisor == 0:
return False, "Error: Division by zero"
return True, dividend / divisor
if __name__ == "__main__":
# Success case
success, r…
How to Use Optional Return in Python Instead of Raising Exceptions
A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.
from typing import Optional
def find_user(users: dict, user_id: int) -> Optional[dict]:
"""
Look up a user by ID. Returns the user dict if found,
otherwise returns None instead of raising KeyError.
"""
return users.get(user_id)
def main() -> None:
users = {
1: {"name": "Alice", "ema…
Browse by section
Each section groups closely related Python snippets.
Errors & debugging — Python code examples
What you will find here
This page collects errors & debugging snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.