Today I learned Mastering Errors and Debugging in Python
When writing code, things don’t always go as planned. Sometimes, your program might run into something unexpected — that's what we call an error. In Python, if an error happens and Python doesn’t know how to handle it, it crashes the program.
Today, I explored the basics of handling errors, debugging, and understanding Python's behavior when something goes wrong. Here's a quick breakdown!
Types of Errors in Python
There are mainly two types of errors you'll encounter as a beginner:
1. Syntax Errors
Syntax errors occur when you break the rules of Python’s language. For example:
print("Hello world"
In the above code, we forgot to close the parenthesis! Python immediately flags this before the program even runs.
2. Runtime Errors
Runtime errors happen while the program is running. A common example:
x = 5 / 0
This will cause a ZeroDivisionError because dividing by zero isn't allowed in mathematics — or Python!
Handling Errors with try-except
To prevent programs from crashing when errors occur, Python gives us the try-except block. It allows us to catch and handle errors gracefully.
Here's an example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result is: {result}")
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
except:
print("Oops! Something went wrong.")
How it works:
Python tries to run the code inside the
tryblock.If it encounters a
ZeroDivisionError, it runs the firstexceptblock.If it encounters a
ValueError(like entering letters instead of numbers), it runs the secondexcept.The last
exceptis a general one — it catches any other unexpected errors.
Debugging Your Code
Debugging is the process of finding and fixing bugs (errors) in your program.
Here’s a simple function with a debug-friendly print statement:
def divide(a, b):
print(f"Dividing {a} by {b}")
return a / b
divide(4, 5)
Adding print statements like this helps you understand what your code is doing at each step.
Understanding Tracebacks
When Python encounters an error it can't handle, it prints a traceback.
A traceback is a report containing the function calls made in your code at a specific point. It’s like a map that helps you track where and why your code broke.
Learning to read tracebacks is a critical skill for every developer!
Bonus Tip: Follow PEP8 Guidelines
PEP8 is Python’s official style guide. It’s a set of recommendations on how to write clean, readable code — things like:
Proper indentation
Naming conventions
Line lengths
Following PEP8 will make your code easier to read and maintain — both for you and others.
Final Thoughts
Errors are a natural part of programming. The key is not to fear them but to understand and handle them properly. With try-except, debugging techniques, and some patience, you can make your programs much more robust and user-friendly.
Happy coding! 🚀