Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Working on a list

In a slightly more interesting example we have a list of values. We would like to divide a number by each one of the values.

As you can see one of the values is 0 which will generate and exception.

The loop will finish early.

def div(a, b):
    print("dividing {} by {} is {}".format(a, b, a/b))

total = 100
values = [2, 5, 0, 4]

for val in values:
    div(total, val)

# dividing 100 by 2 is 50.0
# dividing 100 by 5 is 20.0
# Traceback (most recent call last):
# ...
# ZeroDivisionError: division by zero

We can't repair the case where the code tries to divide by 0, but it would be nice if we could get the rest of the results as well.