Python: Zero to Hero
Learn to program from nothing, in Python: values, decisions, loops, functions and collections, then files, classes and the features that make Python feel like Python. Every idea is a short program you read, predict and fix.
- Beginner
- 8 units, 24 lessons, 309 exercises
- Python
- No experience needed
Unit 01 · 3 lessons
First steps
Read a short program line by line and say exactly what it shows
- 01Values and expressions
Numbers, text, print and arithmetic
- 02Variables
Names for values, types and f-strings
- BOSSA receipt
A formatted total, and your first error messages
Read the unit guide
A program is a list of instructions. Python runs them one line at a time, from the top to the bottom. print(...) is the instruction that shows a value on the screen, and it is how a program tells you what it worked out.
Values come in types. Whole numbers are int, numbers with a decimal point are float, text in quotes is a string (str), and True and False are bool. The type decides what an operator does: 2 + 3 adds, "2" + "3" joins and gives "23", and "2" + 3 is an error. int("30") and str(30) convert between text and numbers.
Arithmetic follows school rules: *, /, // and % before + and -, brackets first. / always gives a float (8 / 2 is 4.0). // divides and drops the remainder, % gives only the remainder, and ** is a power.
A variable is a name for a value. price = 4 means "from now on, price refers to 4". It is an instruction, not a fact: score = score + 5 works out the right-hand side with the old value, then moves the name to the result. Choose names that say what they hold.
An f-string builds text from values: f"{name} is {age}" swaps each pair of curly brackets for the value inside. Add :.2f to show a number with two decimal places, which is how money is printed.
When something goes wrong, read the last line of the error first. NameError means a name Python has not been given yet: a typo, or a line in the wrong order. TypeError means values of the wrong type for an operation. SyntaxError means the text is not valid Python, and then nothing runs at all.
Unit 02 · 3 lessons
Decisions and loops
Trace a program that chooses and repeats, and find the off-by-one mistake
- 01Conditions
Comparisons, if, elif and else
- 02Loops
while, for, range, break and continue
- BOSSFizzBuzz and friends
Loops and conditions working together
Read the unit guide
A comparison asks a question and gives a bool: 3 < 5 is True. The operators are ==, !=, <, >, <= and >=. One = gives a name a value; two == compare. and needs both sides true, or needs at least one, and not flips.
if runs its indented block only when its question is true. elif asks another question only if every earlier one was false, and else catches whatever is left. Exactly one block of a chain runs: the first whose question is true. So the order of the questions matters, and the narrowest question goes first.
Indentation is the structure. The lines indented under an if or a loop belong to it; the first line that goes back to the left margin does not. Use four spaces.
A while loop repeats its block for as long as its question stays true. It needs three things: a start value, a test, and a change inside the block that will one day make the test false. Forget the change and the loop never ends.
A for loop runs its block once for each value it is handed. range(4) hands out 0, 1, 2, 3, and range(2, 5) hands out 2, 3, 4: it starts where you say and stops just before the end value. break leaves a loop at once; continue skips to the next pass.
To understand a loop, trace it: draw a table with a row for each pass and a column for each name. The classic mistake is being off by one: a range that stops one short, or a test with < where <= was meant. Check the first and the last pass.
Unit 03 · 3 lessons
Functions
Write small functions that return values, and combine them into bigger ones
- 01Defining functions
def, parameters, arguments and return
- 02Scope and arguments
Local names, defaults and keyword arguments
- BOSSA text toolkit
Small functions, tested and combined
Read the unit guide
A function is a named block of code. def defines it: Python remembers the block but does not run it. Writing the name with brackets calls it, and the block runs then. Define once, call as often as you like.
Parameters are the names in the def line; arguments are the values in the call. Arguments fill the parameters from left to right, unless the call names them (divide(bottom=4, top=2)). A parameter with a default, such as exp=2, may be left out of the call.
return ends the function and hands a value back: the call becomes that value, so it can be stored, printed or passed to another function. print only shows something to a person; the program cannot use it afterwards. A function that never reaches a return hands back None.
Names made inside a function, parameters included, are local: they exist only while that call is running. A function can read a global name, but assigning to a name inside a function creates a new local one and leaves the global alone. Get results out with return, not by reaching for outside names.
Small functions that each do one job are easy to name, test and reuse. Put the checks next to the code: assert is_palindrome("level") says nothing when it is true and stops the program when it is false.
The classic mistakes: printing where you meant to return, calling a function and throwing its result away, and expecting a function to change a global by assigning to it.
Unit 04 · 3 lessons
Collections
Keep many values in lists and dictionaries, and turn them into a report
- 01Lists
Indexes, slices, changing a list, sharing one
- 02Dictionaries, tuples and sets
Look up by key, unpack pairs, remember what you saw
- BOSSA gradebook
Averages, the best student, groups and a sorted report
Read the unit guide
A list keeps values in order: [70, 85, 90]. Each value has an index, counted from 0, so the last index is always len(nums) - 1. Negative indexes count from the end: nums[-1] is the last item. A slice nums[1:3] copies part of a list, from the start index up to but not including the stop index, the same rule as range.
Lists can change. append adds at the end, insert adds at an index, pop removes the last item and hands it back, and nums[0] = 5 replaces an item. Because a list can change, sharing matters: b = a gives one list a second name, and a change through either name shows through both. a[:] makes a real copy.
A dictionary maps keys to values: {"Ada": 36}. d[key] looks a value up and d[key] = value adds or replaces. A missing key is a KeyError, so use d.get(key, 0) when it might not be there. for key, value in d.items() walks through the pairs.
A tuple is a small fixed group, (3, 7), which cannot be changed and can be unpacked into names: x, y = point. A set holds each value once and answers "have I seen this?" quickly.
Three patterns do most of the work. Counting: count[w] = count.get(w, 0) + 1. Finding the best: start with the first item and replace it whenever a better one turns up. Grouping: a dictionary whose values are lists, with a new empty list for each new key.
The built-ins sum, max, min and sorted save many loops. sorted returns a new list and leaves the original alone. The pitfalls of the unit: an index one past the end, a second name mistaken for a copy, and an average of an empty list.
Unit 05 · 3 lessons
Text and data
Cut text apart, reshape lists and dictionaries in one line, and turn raw lines into a report
- 01Strings
Methods that cut, clean and rebuild text
- 02Comprehensions and sorting
Build, sort and sum up collections in one line
- BOSSA log report
Parse lines into records, count them, rank them, report
Read the unit guide
A string never changes in place. Every string method (upper, strip, replace) gives back a new string and leaves the old one alone, so you keep the result with a name: name = name.strip(). You met methods on lists; strings have many more.
split cuts a string into a list of pieces and join glues a list of strings back into one. With no argument, split() cuts at any run of spaces. find gives the index where a piece of text starts, or -1 when it is not there. Slices work on strings just as they do on lists: code[4:8], code[-4:].
Inside an f-string, a colon starts a format: {price:.2f} shows two digits after the point, {n:>5} pushes the value to the right of five columns, {total:,} adds commas to thousands.
A comprehension builds a collection in one line: [n * 2 for n in nums if n > 0]. Read it left to right as "this value, for each item, if this is true". Curly brackets build a set, and {key: value for ...} builds a dictionary.
sorted returns a new sorted list. key= takes a function that is called on every item, and the results decide the order; reverse=True puts the biggest first. enumerate numbers the items of a loop, zip walks two lists side by side, and sum, min, max, any and all each boil a collection down to one value.
Most real programs are the boss of this unit in disguise: parse each line of text into a record, count or group the records in a dictionary, sort the result, print a report. The classic pitfall is trusting the input. An empty line or one field too few will stop the program unless you check first.
Unit 06 · 3 lessons
Errors, files and modules
Read a traceback, handle the errors you expect, and keep data in files between runs
- 01Exceptions
Read a traceback, then catch the errors you expect
- 02Files and modules
Borrow ready-made code, and keep data after the program ends
- BOSSAn inventory that saves itself
Load, check, update and save stock without losing it
Read the unit guide
When a program stops, Python prints a traceback. Read it from the bottom: the last line names the kind of error and says what went wrong. The lines above are the path the program took to get there, and the File ... line entry closest to the bottom is the line that was running.
try runs a block of lines. If one of them fails with the error named after except, the rest of the block is skipped and the except block runs instead. else runs only when nothing failed, and finally runs every time, error or not. raise creates an error on purpose: it is how your own function says "I refuse".
Catch the narrowest error you expect: ValueError for text that is not a number, KeyError for a missing key, FileNotFoundError for a missing file. Never hide everything behind except Exception. A typo is a bug, not bad luck, and a bug should stop the program loudly so you can fix it.
A module is a file of ready-made code. import math loads one, and then math.sqrt is a function inside it. Python ships with a whole standard library of them: math, random, datetime, pathlib, json and hundreds more.
with open(path, mode) as f: opens a file and closes it again when the block ends. The mode "w" writes and wipes what was there, "a" adds to the end, and no mode means read. Lines in a file end with the newline character \n, and it is still attached when you read them.
JSON is a text format for lists and dictionaries. json.dump(data, f) writes data to a file and json.load(f) reads it back, which is how a program remembers things between runs. Data that comes from a file may be missing or damaged, so load it inside try and check it before you trust it.
Unit 07 · 3 lessons
Objects
Write classes that keep data and its rules together, and make them work with each other
- 01Classes
Make your own kind of value, with its own data and methods
- 02Objects working together
One object holds another, or one class builds on another
- BOSSA bank
Accounts, transfers and a history, with rules nobody can skip
Read the unit guide
A class is a pattern for making values of your own kind. Each value made from it is an object, also called an instance. Dog("Rex") makes one, and Python runs the class's __init__ method to set it up. Variables that live on an object, like self.name, are its attributes, and every object has its own.
A method is a function written inside a class. Its first parameter is always self: the object the method was called on. You never pass it yourself. rex.speak() hands rex in as self. Leave self out of the def line and Python complains that the method "takes 0 positional arguments but 1 was given".
Methods with two underscores on each side are called by Python itself. __init__ runs when an object is made, __repr__ says how to show it, and __eq__ decides what == means. Without __eq__, two objects are equal only if they are the very same object.
Objects work together in two ways. One object can hold others in its attributes: a playlist has songs. Or a class can inherit: class Cat(Animal) gets everything Animal has, can replace a method by defining it again, and can call the old version with super(). Inherit only when one thing really is a kind of the other. Otherwise, hold.
@property lets a method be read like an attribute, so a value such as an area is worked out fresh every time. @dataclass writes __init__, __repr__ and __eq__ for you from a list of names and types.
The reason for all of it is in the boss: rules live with the data. A bank account as a plain dictionary can be set to any nonsense by any line of code. An account class refuses, by raising an error in the one method every change has to pass through.
Unit 08 · 3 lessons
Hero
Pass functions around, make values one at a time, and build a whole program from an empty file
- 01Functions as values
Pass functions around, write tiny ones, wrap one in another
- 02Generators and type hints
Values made one at a time, and notes about types
- BOSSA task manager
One whole program: model, commands, saving, tests, refactor
Read the unit guide
A function is a value like any other. Its name without brackets is the function itself; brackets call it. So a function can be stored in a variable, put in a list or a dictionary, passed to another function and returned from one. sorted(words, key=len) was already doing this.
lambda writes a tiny function with no name, right where it is needed: key=lambda pair: pair[1]. A function defined inside another one remembers the variables around it, which is called a closure. *args gathers any number of arguments into a tuple and **kwargs gathers named ones into a dictionary. A decorator puts all of this together: it takes a function and returns a new one that wraps it, and @name above a def applies it.
A function with yield is a generator. Calling it runs nothing. Each time a loop asks for a value, the function runs to the next yield, hands that value over and pauses. Values are made one at a time, so a generator can walk through a huge file, or never end at all, without filling memory. It can be used once: after the last value it is empty.
Type hints say what a function expects and returns: def average(nums: list[float]) -> float. Python ignores them when the program runs. Editors and checkers read them and warn you before you run anything, and so does the next person to read your code.
The capstone builds a task manager the way real programs are built: a data model first, then commands as small functions, then saving and loading, then tests. A test calls your code with known input and uses assert to check the result. Run the tests after every change.
A refactor changes how code is organised without changing what it does. The tests are what make it safe: if they still pass, you broke nothing.
Learn Python: Zero to Hero on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.