A Professional’s Tutorial to Python Try + Except
Try + except, even more Python control flow + error checking
Welcome to eighth, in a series of tutorials that teach beginner Python specifically for aspiring data scientists. For an overview of these tutorials, click here.
Building upon the foundation established in our previous tutorial on crafting a Python guessing game, we are now poised to explore a crucial aspect of Python programming: exception handling using
If you have yet to familiarize yourself with the foundational constructs presented in the earlier tutorials, it's advisable to reference the overview to all tutorials in this series.
Exception handling, while perhaps a divergence from the playful context of a guessing game, is an indispensable tool for aspiring data scientists who plan to use Python in their work. Whether it’s in the context of data science, software development, or scripting, the robust management of potential errors can make the difference between a seamless user experience and a program that crashes unexpectedly.
In simplest terms, an exception is an event that disrupts the normal flow of a program’s execution. Exceptions are often thought of as errors. Because usually an exception is the result of an error. They’re ugly. They look like this.
print(100 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Common scenarios that give rise to exceptions include:
- Reading a file that doesn’t exist.
- Dividing a number by zero.
- Accessing a non-existent dictionary key.
- Casting an incompatible data type, like converting a string with alphabetic characters to an integer.
Python, in its wisdom (infinite wisdom-I kid), raises an exception when it encounters such situations, offering programmers an…