Introduction to errors

Intermediate Python for Developers

George Boorman

Curriculum Manager, DataCamp

What is an error?

  • Code that violates one or more rules
  • Error = Exception
  • Cause our code to terminate!

Hierarchy of some Python exceptions

1 https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Intermediate Python for Developers

TypeError

  • Incorrect data type
"Hello" + 5

TypeError output showing strings and integers cannot be combined

Intermediate Python for Developers

ValueError

float("Hello")

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

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

Output showing the result 2.0 without an error

Intermediate Python for Developers

Tracebacks

Traceback message

Intermediate Python for Developers

Tracebacks

Traceback message highlighting the error type

Intermediate Python for Developers

Tracebacks

Traceback message highlight the code that caused the error

Intermediate Python for Developers

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
Intermediate Python for Developers

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"]
Intermediate Python for Developers

Tracebacks from packages

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

Intermediate Python for Developers

Tracebacks from packages

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

Intermediate Python for Developers

Tracebacks from packages

Traceback showing the line in our code that caused the error

Intermediate Python for Developers

Tracebacks from packages

Traceback showing code that intentionally returns an error

Intermediate Python for Developers

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...