Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
How to Handle ValueError with try-except in Python
Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.
def get_number(prompt="Enter a number: "):
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("That's not a valid number. Please try again.")
def divide_numbers(a, b):
try:
result = a / b
return result
ex…
How to handle ZeroDivisionError in Python
Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.
def safe_divide(a, b):
"""Return a/b if possible, else None when dividing by zero."""
try:
return a / b
except ZeroDivisionError:
return None
def safe_divide_with_message(a, b):
"""Return a how-to message on divide-by-zero error."""
try:
return a / b
except ZeroDivisio…
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.