A Professional’s Tutorial to Python Try + Except

Try + except, even more Python control flow + error checking

Adam Ross Nelson
8 min readSep 17

For an overview of these tutorials, click here (or click the image).

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 try and except.

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.

Multiple spheres. Close up image. Most are black and in a line. One is bright yellow and out of line.
Image Credit: Author’s illustration created in Canva.com.

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.

Understanding Exceptions

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…

Adam Ross Nelson

Ask about my free career course. I mentor new (💫) and aspiring data scientists enter (🚪) and level up (📈) in the field.