Miscellaneous Python things

In this session, we'll talk about:

  • More control flow tools: try/except, break and continue
  • A few other built-in Python functions
  • Installing third-party modules

Handling errors with try/except

Sometimes your script will throw errors. When it does, sometimes you want the script to continue after handling the error in some way. Let's take a look at some examples.

What happens when we run the code below?


In [ ]:
humans = [
    {'name': 'Cody', 'age': 32, 'job': 'Training director', 'height_in': 72},
    {'name': 'Jeff', 'age': 44, 'job': 'Snake charmer', 'height_in': 60},
    {'name': 'Sally', 'age': 55, 'job': 'Fry cook'}
]

for human in humans:
    print(human['name'], 'is', human['height_in'], 'inches tall')

Let's catch the KeyError. You could use a bare except statement, which would fire if any exception is raised, but it's good practice to specify the class of error that you're controlling for.


In [ ]:
humans = [
    {'name': 'Cody', 'age': 32, 'job': 'Training director', 'height_in': 72},
    {'name': 'Jeff', 'age': 44, 'job': 'Snake charmer', 'height_in': 60},
    {'name': 'Sally', 'age': 55, 'job': 'Fry cook'}
]

for human in humans:
    try:
        print(human['name'], 'is', human['height_in'], 'inches tall')
    except KeyError:
        print('We don\'t know how tall', human['name'], 'is')

Break and continue

These statements are frequently used in loops to control the flow of your program. We'll use range() to demo how each statement works.

  • break breaks out of the loop
  • continue skips to the next iteration

In [ ]:
# break
for x in range(10):
    if x == 7:
        break
    else:
        print(x)

In [ ]:
# continue
for x in range(10):
    if x == 7:
        continue
    else:
        print(x)

Other built-in functions

Check out the full list here. We're just going to look at a couple.

dir()

Use the dir() function to see all of the attributes and methods available to an object -- this is often how I learn about new ways to manipulate data!

Let's try it out on some different data types.


In [ ]:
# string
dir('hello!')

In [ ]:
# lists
l = [1, 2, 3, 4, 5, 6]
dir(l)

In [ ]:
# dicts
d = {'name': 'Cody', 'age': 32, 'job': 'Training director', 'height_in': 72}

dir(d)

enumerate()

Use enumerate() in a loop to keep track of where you're at in the loop -- the index. Notice that we then need to use two variables in the loop -- the index and the actual value.


In [ ]:
humans = [
    {'name': 'Cody', 'age': 32, 'job': 'Training director', 'height_in': 72},
    {'name': 'Jeff', 'age': 44, 'job': 'Snake charmer', 'height_in': 60},
    {'name': 'Sally', 'age': 55, 'job': 'Fry cook'}
]

for idx, human in enumerate(humans):
    print(idx, human['name'])

zip() and dict()

Use zip to fold multiple iterable objects into one thing. My favorite use of zip is turning two lists of related data into a single dictionary using dict() to coerce the zip object:


In [ ]:
names = ['Cody', 'Jeff', 'Sally']
ages = [32, 44, 55]

zip_obj = zip(names, ages)

human_dict = dict(zip_obj)

print(human_dict)

sum(), max() and min()

  • Sum a list of numbers
  • Find the highest value in a list
  • Find the lowest value in a list

In [ ]:
# a list of numbers
l = [1100, 200, 9400, 800, 1000]

# sum
total = sum(l)

# max
max_value = max(l)

# min
min_value = min(l)

# print the results
print(total, max_value, min_value)

Installing third-party packages

Use the pip package manager to install third-party packages. The pip tool comes bundled with Python 3. To install a module system-wide, you'd run this command from the Terminal app: pip install name_of_your_package.

A saner approach would be to use a "virtual environment" and install dependencies specifically for each project. That way, you avoid the problem of "I need version X of pandas for this project but version Y for this other project." If pandas is installed globally on your computer, you'll quickly run into problems.

For this boot camp, we have installed these packages:

  • jupyter
  • bs4 (Beautiful Soup)
  • requests
  • pandas
  • matplotlib

Each of these packages, in turn, has dependencies that are automatically installed.