Up Next: Building Real Programs

Look back at what Module 2 taught, functions, lists, tuples, dictionaries, sets, comprehensions and sorting, try a grade book of your own that uses all of it, and see what Module 3 adds, files, packages, error handling and classes.

Apprentice · Python · Updated

By

After this lesson you can

  • Describe what files, modules, exceptions and classes will let your programs do

Key takeaways

  • After Module 2 you can package each job in a function, and organize real data in lists, tuples, dictionaries and sets.
  • Comprehensions and sorted() with a key reshape that data in a line or two.
  • A grade book for one class, a dictionary of students to their lists of scores, puts every one of those tools to work.
  • So far a program forgets everything when it ends, lives in one file, and stops at the first answer it can't use. Module 3 fixes all three, and adds classes for your own kinds of things.

When this module started, a program could hold one value per variable and do one job at a time. Now look at what you can write: functions that each do one job, and data organized the way the real world organizes it, in lists, records and groups. That's most of what working programmers do with Python every day.

This lesson looks back at what you can do, gives you a project to try with all of it, and shows what Module 3 adds: the pieces that turn a script into a real program.

What you can do now

After Module 2, you can:

  • package a job in a function, with parameters, a return value, default values and keyword arguments, and keep its variables local;
  • keep things in order in a list: add, remove, loop, slice and sort them;
  • keep a fixed group together in a tuple, and unpack it into names;
  • look things up by name in a dictionary, and loop through its pairs with .items();
  • read nested data, a list of dictionaries or a dictionary of lists;
  • drop duplicates and compare groups with sets;
  • build a new collection in one line with a comprehension, and sort by anything with a key.

Here's a program that uses nearly all of it, on a week of a step-counter app's walks:

def average(numbers):
    return sum(numbers) / len(numbers)


week = {
    "Maya": [8400, 10200, 7600],
    "Leo": [12000, 11500, 9800],
    "Ana": [5200, 6100, 7000],
}

averages = {name: round(average(steps)) for name, steps in week.items()}
over_goal = [name for name, steps in averages.items() if steps >= 8000]
ranking = sorted(averages.items(), key=lambda pair: pair[1], reverse=True)

print(averages)
print("Over 8000 a day:", over_goal)
for name, steps in ranking:
    print(f"{name}: {steps} steps a day")
{'Maya': 8733, 'Leo': 11100, 'Ana': 6100}
Over 8000 a day: ['Maya', 'Leo']
Leo: 11100 steps a day
Maya: 8733 steps a day
Ana: 6100 steps a day

A function, a dictionary of lists, a dictionary comprehension, a list comprehension, and a sort by value: you can read every line of it.

Try it: a grade book of your own

The best way to find out how much you can do is to build something with no step-by-step instructions. Try a grade book for one class, with only what you know now:

  • The data: a dictionary of each student's first name to a list of their scores, such as {"Maya": [92, 88, 95], "Leo": [71, 64, 80]}, with five or six students.
  • Each student's average, from a function that takes a list of scores and returns their average.
  • A letter grade, from a function with if and elif: 90 and up is an A, 80 and up a B, and so on.
  • The class average, the average of every student's average.
  • The top three, sorted by average with a key, the highest first.
  • Who's below a passing line, such as 70, built with a comprehension.
  • A printed report that puts it all on the screen, one student per line.

Write one function at a time, and call it with a student or two before you move on. There's no test suite for this one: when the report prints what you worked out by hand, it works.

Where your programs hit a wall

Three things limit every program you can write so far:

  • It forgets everything when it ends. The pantry, the scores, the steps: they're typed into the program, and any change is gone when it stops.
  • It's one file. As a program grows, one long file gets hard to find your way around, and code you'd like to reuse in another program is stuck inside it.
  • It stops at the first answer it can't use. When someone types ten where a number belongs, int("ten") stops the whole program with a ValueError.

What Module 3 unlocks

Module 3 builds programs the way real ones are built:

  • Modules and packages: split a program into files, use Python's standard library, and install packages other people wrote with pip, each project in its own virtual environment.
  • Errors and debugging: catch an error with try and except and give the user a friendly message, raise your own errors, and step through a program line by line in VS Code's debugger.
  • Files: read and write text files, CSV files and JSON files, so a program remembers its data between runs.
  • Classes: describe your own kinds of things, such as a houseplant with a watering schedule, with their data and the functions that belong to them.

Here's a sneak peek at two of them. The json module turns a dictionary into JSON text a file can hold, and try with except catches the error that would have stopped the program:

import json

pantry = {"eggs": 6, "flour": 4}
print(json.dumps(pantry))

try:
    servings = int("ten")
except ValueError:
    print("Please type the servings as a number, such as 10.")
{"eggs": 6, "flour": 4}
Please type the servings as a number, such as 10.

You don't need to understand every part of it yet: that's what Module 3 is for.

Check yourself

2 questions to try on the lesson page.

So what

Module 2 gave your programs real data to work with. Module 3 lets them keep it, share it across files, survive a bad answer, and describe your own kinds of things.

Key terms

Related