Chapter 12

Building Better Programs

Knowing the syntax is not enough. Good programmers also organize, test, debug, and simplify.

Chapter 12, Building Better Programs

What you will learn

  • Combine functions and data structures.
  • Use nested data without losing track of shape.
  • Understand basic comprehensions.
  • Use a repeatable debugging and testing process.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

12.1 Separate Jobs into Functions

Type this into a file, predict the output, then run it.

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

def show_summary(numbers):
    print("Count:", len(numbers))
    print("Average:", average(numbers))
    print("Minimum:", min(numbers))
    print("Maximum:", max(numbers))

scores = [70, 85, 92, 60, 78]
show_summary(scores)

12.2 Nested Data

TPRM Lab 12.2: A List of Dictionaries

Type this into a file, predict the output, then run it.

Python
students = [
    {"name": "Ava", "scores": [80, 90]},
    {"name": "Noah", "scores": [72, 88]}
]

for student in students:
    avg = sum(student["scores"]) / len(student["scores"])
    print(student["name"], avg)

12.3 Comprehensions: Useful, but Not a Contest

Type this into a file, predict the output, then run it.

Python
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
evens = [n for n in numbers if n % 2 == 0]

print(squares)
print(evens)

Back to Python the TPRM Way