Introduction to errors

Python intermedio per sviluppatori

Jasmin Ludolf

Senior Data Science Content Developer

What is an error?

  • Code that violates a rule
  • Error = Exception
  • Cause our program to terminate!

Hierarchy of some Python exceptions

1 https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Python intermedio per sviluppatori

TypeError

  • Incompatible data type
"Hello" + 5

TypeError output showing strings and integers cannot be combined

Python intermedio per sviluppatori

ValueError

float("Hello")

ValueError output confirming that the string 'Hello' cannot be converred to a float

  • The value is not within an acceptable range
float("2")

Output showing the result 2.0 without an error

Python intermedio per sviluppatori

Tracebacks

Traceback message

Python intermedio per sviluppatori

Tracebacks

Traceback message highlighting the error type

Python intermedio per sviluppatori

Tracebacks

Traceback message highlight the code that caused the error

Python intermedio per sviluppatori

Code in packages

  • Packages contain other people's code, e.g., custom functions
  • Known as source code
  • pip install <package> downloads source code to our local environment
  • The pandas' pd.read_csv() function executes the code written for that custom function behind the scenes
Python intermedio per sviluppatori

Tracebacks from packages

# Import pandas package
import pandas as pd

# Create pandas DataFrame                 
products = pd.DataFrame({"ID": "ABC1",
                         "price": 29.99})

# Try to access the non-existent "tag" column
products["tag"]
Python intermedio per sviluppatori

Tracebacks from packages

Traceback from trying to subset a pandas DataFrame on a non-existent column

Python intermedio per sviluppatori

Tracebacks from packages

Traceback showing the file that produced an error when executed, along with the error type of KeyError

Python intermedio per sviluppatori

Tracebacks from packages

Traceback with line 3803 highlighted

Python intermedio per sviluppatori

Tracebacks from packages

Traceback with base.py highltigted

Python intermedio per sviluppatori

Tracebacks from packages

Traceback with KeyError highlitghted

Python intermedio per sviluppatori

Tracebacks from packages

Traceback showing the line in our code that caused the error

Python intermedio per sviluppatori

Tracebacks from packages

Traceback showing code that intentionally returns an error

Python intermedio per sviluppatori

Tracebacks from packages

Traceback with Raised highligted

Python intermedio per sviluppatori

Let's practice!

Python intermedio per sviluppatori

Preparing Video For Download...