Mastering a language you already use
If you finished the Start level of Lumenary CS, you can already write Python: you know variables, if, for, functions, lists and dictionaries. So why a whole course on Python itself?
Because knowing enough Python to get a program working and knowing Python well are very different things. A beginner writes for i in range(len(names)): and indexes into two lists; an experienced programmer writes for name, score in zip(names, scores):. A beginner is surprised when changing one list changes another; an experienced programmer knows exactly which names refer to which objects. A beginner sees @dataclass or async def or with in someone else's code as magic; an experienced programmer knows each is a small, documented protocol and could write their own.
That gap is what this course closes. Python is one of the most used programming languages in the world: it runs scripts that glue systems together, web back ends, scientific pipelines, most machine-learning research, and a good share of the world's teaching. The same language is used by a biologist cleaning a spreadsheet and by an engineer serving millions of requests, and the difference between their code is mostly the material in these ten lessons.
This first lesson does three things. It tells you where Python came from and how it changes, because that explains a lot of its design. It makes sure you can run Python properly on your own machine. And it starts the real work: the object model, the handful of rules about names and objects that every other part of the language rests on.
From a Christmas project to a steering council
Python began in December 1989, when Guido van Rossum, a programmer at the CWI research institute in Amsterdam, started writing an interpreter over the Christmas holidays. He had worked on ABC, a teaching language with clean syntax and indentation-based blocks that never caught on outside its niche, and he wanted something with ABC's readability that could also talk to the operating system and be extended in C. He named it after the BBC comedy series Monty Python's Flying Circus. Version 0.9.0 was posted publicly in February 1991, which is why the language's year is usually given as 1991.
A few milestones explain a lot of what you will meet:
- Python 2.0 (2000) brought list comprehensions, a garbage collector that can reclaim reference cycles, and an open, community-driven development process.
- Python 3.0 (2008) deliberately broke compatibility to fix old mistakes: text became Unicode
strseparate frombytes,printbecame a function, integer division got its own operator//. The migration took over a decade; Python 2 reached its end of life on 1 January 2020. If you find old code withprint "hello", that is Python 2. - The PEP process. Since 2000, every significant change is written up as a Python Enhancement Proposal: a public design document with a motivation, a specification and the rejected alternatives. Reading PEPs is the best way to learn why Python works as it does, and this course links them often.
- Governance. For almost thirty years van Rossum had the final word, with the half-joking title "Benevolent Dictator For Life". He stepped down in July 2018, after a draining argument over the
:=operator, and since 2019 a steering council of five people, elected by the core developers each year, decides on PEPs (PEP 13). - An annual rhythm. Since Python 3.9, a new feature release arrives every October (PEP 602) and each one is supported for about five years. Python 3.11 made the interpreter markedly faster, 3.13 shipped a new interactive shell and an experimental build without the global interpreter lock, 3.14 (October 2025) made that free-threaded build officially supported, and 3.15 (9 October 2026) added lazy imports, a built-in
frozendictand UTF-8 as the default text encoding everywhere. The status page always shows which versions are current; as of late 2026 that is 3.15, with 3.14 still receiving bug fixes and 3.10 just past its end of life.
Python's priorities are summed up in The Zen of Python by Tim Peters, nineteen short aphorisms you can read by typing import this at the Python prompt. Two of them, quoted from PEP 20, are worth keeping in mind for this whole course: "Readability counts." and "There should be one-- and preferably only one --obvious way to do it." Much of what makes code Pythonic is choosing the obvious, readable way that the rest of the community will recognise at a glance.
Installing and running Python
When people say "Python" they usually mean CPython, the reference implementation, written in C and maintained by the core developers. Other implementations exist: PyPy (with a just-in-time compiler), MicroPython (for microcontrollers), GraalPy (on the JVM) and Pyodide, which is CPython compiled to WebAssembly and is what runs the Run buttons in these lessons.
To install CPython:
- Windows and macOS: use the installer from python.org/downloads.
- Linux: your distribution almost certainly ships a Python, but it may be several versions old and it belongs to the operating system; install a newer one from python.org, your distribution's newer packages, or a version manager.
- Any platform: many professionals now use uv, a fast project and package manager that can also install Python versions (
uv python install 3.15). Lesson 8 covers it properly.
Then check what you have. On Windows the command is usually py; elsewhere it is python3:
python3 --versionThere are four everyday ways to run code, and you should know all of them:
python3 # the interactive shell (the REPL): try things out
python3 hello.py # run a script file
python3 -c "print(2 ** 100)" # run one line from the command line
python3 -m http.server # run a module from the standard library (or your package) as a programThe REPL (read-evaluate-print loop) is where experienced programmers test an idea before writing it into a file. Since 3.13 it has colour, multi-line editing and history. Two built-ins make it a learning tool: help(obj) shows documentation and dir(obj) lists an object's attributes. Try help(str.split) or dir([]).
Here is a first complete program. The if __name__ == "__main__": line at the end means "run main() only when this file is executed directly, not when another file imports it"; you will see this in almost every script, and lesson 8 explains how it works.
"""greet.py: a first script, written the way professionals lay one out."""
import sys
def greeting(name: str, hour: int) -> str:
if hour < 12:
part = "morning"
elif hour < 18:
part = "afternoon"
else:
part = "evening"
return f"Good {part}, {name}!"
def main() -> None:
for name, hour in [("Amara", 9), ("Kenji", 14), ("Lucía", 20)]:
print(greeting(name, hour))
print("Running on Python 3.10 or newer:", sys.version_info >= (3, 10))
if __name__ == "__main__":
main()It prints:
Good morning, Amara!
Good afternoon, Kenji!
Good evening, Lucía!
Running on Python 3.10 or newer: TrueThe name: str and -> str are type hints. Python ignores them when running the program; they are there for readers and for tools, and lesson 6 is about them.
Names are labels; objects are things
Everything Python manipulates is an object: numbers, strings, lists, functions, classes, modules, even None. Every object has three things:
- an identity, which never changes while the object exists (
id(obj)returns it as a number, anda is basks whether two expressions give the same object); - a type, which also never changes and decides what the object can do (
type(obj)); - a value, which for some objects can change.
A variable is not a box that holds a value. It is a name bound to an object. The statement x = [1, 2] creates a list object and binds the name x to it; y = x binds a second name to the same object. Nothing is copied. This is the single most important rule in Python, and most surprises beginners meet come from forgetting it.
"""Names, identity and mutation."""
scores = [72, 88, 95]
backup = scores # a second name for the same list
scores.append(61) # mutate the object...
print(backup) # ...and every name that refers to it sees the change
print(backup is scores)
copy = list(scores) # a new list containing the same items
print(copy == scores, copy is scores)
copy.append(100)
print(scores)
print(copy)
word = "tide"
alias = word
word += "s" # str is immutable: += builds a new string and rebinds word
print(word, alias)[72, 88, 95, 61]
True
True False
[72, 88, 95, 61]
[72, 88, 95, 61, 100]
tides tideLook at the last two lines. Lists are mutable: append changes the object in place, so every name bound to it sees the change. Strings are immutable: there is no way to change a str object, so word += "s" creates a new string and rebinds word to it, leaving alias on the old one. The built-in immutable types are numbers, str, bytes, tuple, frozenset, bool and None; list, dict, set and bytearray are mutable, and so are instances of your own classes unless you design them not to be.
== and is ask different questions. == asks "do these have equal values?" and each type decides what that means. is asks "are these the same object?" and nothing can override it. Use is for singletons, almost always None (if result is None:), and == for everything else.
Function calls share objects too
When you call a function, each parameter becomes a new name bound to the object the caller passed. Nothing is copied, and nothing is passed "by reference" in the C++ sense either: the Python FAQ describes it as passing by assignment. So a function can mutate a mutable argument, and the caller will see it, but rebinding a parameter only changes the function's own name.
"""Arguments are bound to the caller's objects."""
def add_tag(tags, tag):
tags.append(tag) # mutates the caller's list
def shout(label):
label = label.upper() + "!" # rebinds the local name only
return label
tags = ["draft"]
add_tag(tags, "urgent")
print(tags)
name = "report"
print(shout(name), name)['draft', 'urgent']
REPORT! reportWhen you need an independent copy, say so: list(xs), xs.copy(), xs[:], dict(d) or copy.copy(obj) make a shallow copy (a new outer container whose items are the same objects), and copy.deepcopy(obj) copies recursively. A shallow copy of a list of lists still shares the inner lists, which is the cause of one exercise below.
Dynamic, strong, and compiled after all
Three words describe how Python treats types and code, and they are often misunderstood.
Definition— Dynamically typed
Types belong to objects, not to names. The name x can be bound to an int now and a str later, and Python checks whether an operation makes sense when it runs, not before.
Definition— Strongly typed
Python does not silently convert between unrelated types. "3" + 4 raises TypeError instead of guessing whether you meant "34" or 7. (Numbers do mix: 1 + 2.5 is 3.5, and True behaves as 1, because bool is a subclass of int.)
Definition— Bytecode
CPython does not run your source text directly. It first compiles each module to bytecode, instructions for CPython's own virtual machine, and then interprets those. Compiled modules are cached in __pycache__ folders as .pyc files so the next import is faster.
You can see the bytecode with the standard library's dis module. The exact instructions change between versions (they are an implementation detail, and 3.11 onwards specialises them while the program runs), so the listing below is what CPython 3.13 printed:
import dis
def average(values):
return sum(values) / len(values)
dis.dis(average) 4 RESUME 0
5 LOAD_GLOBAL 1 (sum + NULL)
LOAD_FAST 0 (values)
CALL 1
LOAD_GLOBAL 3 (len + NULL)
LOAD_FAST 0 (values)
CALL 1
BINARY_OP 11 (/)
RETURN_VALUEYou never need to read bytecode to write good Python, but knowing it exists explains things: why the first run of a big program is slower than the next, why some errors (a SyntaxError) are reported before anything runs while others (a NameError) appear only when a line executes, and how tools such as coverage and debuggers work.
Idioms you will see everywhere
Pythonic code leans on a small set of idioms. None is complicated, and together they make code shorter and easier to read. Run this block and change it:
# Unpacking: assign several names at once, swap without a temporary, collect the rest with *
first, *middle, last = [3, 1, 4, 1, 5, 9]
print(first, middle, last)
a, b = 1, 2
a, b = b, a
print(a, b)
# Truthiness: empty containers, zero, None and "" are false; almost everything else is true
for value in [0, 7, "", "hi", [], [0], None]:
print(f"{value!r:>5} is {'truthy' if value else 'falsy'}")
# enumerate and zip instead of index arithmetic
stalls = ["tamales", "jollof", "pho"]
orders = [41, 57, 1203]
for rank, (stall, count) in enumerate(zip(stalls, orders, strict=True), start=1):
print(f"{rank}. {stall:<8}{count:>6,}")
# f-strings: = shows the expression as well as its value; after : comes a format spec
total = sum(orders)
print(f"{total=}, {total / len(orders)=:.1f}")
# Chained comparisons, and := to name a value inside an expression
if 0 < (n := len(stalls)) <= 10:
print(f"{n} stalls: a manageable market")3 [1, 4, 1, 5] 9
2 1
0 is falsy
7 is truthy
'' is falsy
'hi' is truthy
[] is falsy
[0] is truthy
None is falsy
1. tamales 41
2. jollof 57
3. pho 1,203
total=1301, total / len(orders)=433.7
3 stalls: a manageable marketA few notes on what you just ran:
zip(..., strict=True)(Python 3.10) raises an error if the lists have different lengths, instead of silently stopping at the shorter one. Use it whenever unequal lengths would be a bug.!rin an f-string usesrepr(), the unambiguous, programmer-facing form (with quotes on strings), instead ofstr().- The
:="walrus" operator (Python 3.8) binds a name inside an expression. It is handy inwhileloops and comprehensions, and easy to overuse; if a plain assignment on the line before reads better, use that. - Truthiness lets you write
if items:instead ofif len(items) > 0:. The only caution is when0or""is a legitimate value that differs from "missing": then testif x is None:explicitly.
Common misconceptions
Misconception
"Variables are boxes that hold values." In Python they are names attached to objects. Assignment never copies; it attaches a name. Once you think in names and objects, aliasing, argument passing and the mutable-default-argument trap (lesson 4) all stop being surprising.
Misconception
"is is a faster or stricter ==." They ask different questions. x is 5 may happen to work in CPython because small integers are cached, but that is an implementation detail, and CPython warns about is with a literal. Use is only for identity, which in practice means None, and sentinels you create yourself.
Misconception
"Python is untyped" or "Python has no compiler." Every object has a definite type that Python enforces at run time, and every module is compiled to bytecode before it runs. What Python lacks by default is a check before running; static checkers such as mypy add that, as lesson 6 shows.
Misconception
"Python is too slow for serious work." Pure Python loops are much slower than C, Rust or Java. But serious Python programs spend most of their time inside code written in faster languages (NumPy, database drivers, PyTorch, the standard library's C modules), and Python's job is to orchestrate them clearly. When the slow part really is your Python code, lesson 10 shows how to find it and what to do.
Exercises
Most exercises ask you to predict output: decide first, then check by running the code (in the REPL or in a Run block above). The last exercise asks for code.
1. The Python way
Warm-upHumanA core developer writes a PEP proposing new syntax. Since 2019, who makes the final decision to accept or reject it?
2. The Python way
Warm-upComputationalWhat does this program print?
point = (1, 2)
saved = point
point += (3,)
print(point, saved)
3. The Python way
CoreComputationalWhat does this program print?
grid = [[0] * 3] * 2
grid[0][0] = 5
print(grid)
4. The Python way
CoreComputationalWhat does this program print?
import copy
team = {"name": "Otters", "members": ["Ana", "Bo"]}
twin = copy.copy(team)
twin["name"] = "Herons"
twin["members"].append("Chidi")
print(team)
5. The Python way
Warm-upComputationalA function find_user(id) returns a user object, or None when there is no such user. Which test for "not found" is the idiomatic one?
6. The Python way
CoreComputationalWhich of these values are falsy (that is, bool(value) is False)? Choose all that apply.
7. The Python way
CoreComputationalWrite unique_in_order(items), which returns a new list containing the items of items with repeats removed, keeping each item's first occurrence in its original position. It must not modify its argument. You may assume the items are hashable.
For example, unique_in_order([3, 1, 3, 2, 1]) is [3, 1, 2].
Further reading and resources
- The Python Tutorial · Python Software FoundationThe official tour of the language. Skim it for anything this course moves through quickly.
- PEP 20: The Zen of Python · Tim Peters
- PEP 13: Python Language GovernanceHow the steering council is elected and what it decides.
- The Python Language Reference: Data model (objects, values and types)
- The Python Standard Library: dis, disassembler for Python bytecode
- Status of Python versions