A bank's recruitment cell has the results of a written test in one text file: three thousand lines, and on each line a roll number, a name and a mark. By evening somebody wants the topper, the number who passed, the names grouped by grade, and the average mark of those who passed. Last chapter you could hold one number or one string at a time. This job is different, because the data comes in thousands and the work is the same for each one.
Python's answer has three pieces. A collection holds many values under one name. A loop visits them one by one. A function gives a job a name, so you write it once and use it everywhere. With those three, the same ten lines serve thirty candidates or three million.
By the end of this chapter you'll be able to choose among a list, a tuple, a set and a dictionary and say why, slice a list, and explain why changing a list through one name can change it through another. You'll write for and while loops, tell exactly which numbers a range produces, and build a new list in a single line with a comprehension. You'll define functions with default, keyword and variable-length arguments, say which variable a name refers to inside a function, and write a recursive function that stops. Last, you'll put it all together in the kind of written answer the exams ask for.
We go in eight parts, from the easy ones to the tricky ones: lists and tuples; sets and dictionaries; decisions and loops; comprehensions; functions; scope and the default argument that remembers; recursion; and finally two complete written answers. Every program here was run with Python 3.12, and every output and error message is the real one. The C versions of loops, functions and recursion have their own chapters; here we meet what Python does differently.