Python is the most popular language for beginners, and also one of the most used by professionals: system administrators write automation in it, data analysts crunch numbers with it, developers build websites and APIs with it, and scientists train machine-learning models with it. It is popular for a simple reason: Python code is short and readable, so you spend your effort on the problem, not on the language. This tutorial takes you from “what is a variable?” to writing classes, reading files, using the standard library, testing your code and building small real programs.
You do not need any earlier experience. Every example was run and tested before this page was published, and the results shown in the comments are the real results. The best way to learn is to type the examples yourself, change them, and break them. When you finish, you will find a practice plan at the end. This guide pairs well with our virtual environments guide and the algorithms tutorial, which uses Python throughout.
Contents
- 1. Installing Python and running your first program
- 2. Variables, numbers and basic types
- 3. Text: strings
- 4. Collections: lists, tuples, dictionaries and sets
- 5. Making decisions and repeating things
- 6. Functions
- 7. Closures, decorators and generators
- 8. Errors and exceptions
- 9. Files, paths, JSON and CSV
- 10. Modules, packages and pip
- 11. Classes and objects
- 12. A tour of the standard library
- 13. Testing your code
- 14. Writing good Python
- 15. Two small projects
- 16. Where to go next, and FAQ
1. Installing Python and running your first program
Install
You need Python 3 (current versions are 3.12, 3.13 and newer; Python 2 is long dead). Pick your system:
winget install Python.Python.3.13 # Windows (or download the installer from python.org; tick "Add python.exe to PATH")
brew install python # macOS with Homebrew
sudo dnf install python3 # Red Hat, Rocky, AlmaLinux, Fedora
sudo apt install python3 python3-pip python3-venv # Debian and Ubuntu
python --version # on Linux and macOS you may need: python3 --version
Three ways to run Python
- The interactive shell (REPL). Type
pythonand you get a prompt>>>where each line runs at once. It is perfect for trying things. Leave withexit(). - A script. Save code in a file such as
hello.pyand runpython hello.py. This is how real programs run. - An editor. Visual Studio Code with its Python extension, or PyCharm, give you colours, hints and a debugger. Jupyter notebooks are popular for data work.
print("Hello, world!") # Hello, world!
print("Python", 3 + 4, "is", "fun") # Python 7 is fun: print joins its arguments with spaces
Everything after a # on a line is a comment, which Python ignores. Write comments to explain why you do something, not what the code obviously does. Unlike many languages, Python uses indentation (four spaces) to group code. This is not decoration: wrong indentation is an error, or worse, a different program.
2. Variables, numbers and basic types
A variable is a name that points to a value. You create it by assigning with =. There is no declaration, and the variable can later point to a value of another type (Python is dynamically typed), but each value itself has a fixed type.
name = "Sara"
age = 31
height = 1.68
is_admin = True
nothing = None # None means "no value"
print(type(name), type(age), type(height), type(is_admin), type(nothing))
# <class 'str'> <class 'int'> <class 'float'> <class 'bool'> <class 'NoneType'>
x = y = 10 # two names, one value
a, b = 1, 2 # assign several at once
a, b = b, a # swap without a temporary variable
print(a, b) # 2 1
Names use letters, digits and underscores, cannot start with a digit, and are case-sensitive. The convention is snake_case for variables and functions and UPPER_CASE for constants. Avoid names that hide built-ins such as list, str or max.
Numbers
print(7 + 2, 7 - 2, 7 * 2) # 9 5 14
print(7 / 2) # 3.5 - / always gives a float
print(7 // 2) # 3 - // is floor division (rounds down)
print(7 % 2) # 1 - % is the remainder
print(2 ** 10) # 1024 - ** is the power
print(-7 // 2) # -4 - floor division rounds toward minus infinity
print(round(3.14159, 2), abs(-5), max(3, 9, 4), min(3, 9, 4), sum([1, 2, 3])) # 3.14 5 9 3 6
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True: compare floats this way
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2")) # 0.3: use Decimal for money
print(10 ** 30) # 1000000000000000000000000000000: integers never overflow
Floating-point numbers are stored in binary, so some decimals (like 0.1) cannot be exact. This is true in every language. For money, use Decimal or whole cents. Python’s integers have no size limit, which is rare and useful.
Converting between types and reading input
print(int("42") + 1, float("3.5"), str(99) + " items", bool(0), bool("hi")) # 43 3.5 99 items False True
print(int(3.9), int("-7")) # 3 -7 (int() cuts the decimals, it does not round)
user = input("Your name? ") # input() always returns text
print("Hello,", user) # Hello, Sara (in this test run the answer was "Sara")
try:
int("abc")
except ValueError as error:
print("Not a number:", error) # Not a number: invalid literal for int() with base 10: 'abc'
Truthiness: in a condition, 0, 0.0, "", [], {}, set() and None count as false; almost everything else is true. This lets you write if items: instead of if len(items) > 0:.
3. Text: strings
A string is a sequence of characters, written in single or double quotes. Strings are immutable: methods never change the original, they return a new string.
s = "Python is fun"
print(len(s), s[0], s[-1]) # 13 P n - indexes start at 0; -1 is the last character
print(s[0:6], s[7:], s[::-1]) # Python is fun nuf si nohtyP - slicing: [start:stop:step]
print("fun" in s, s.startswith("Py"), s.endswith("!")) # True True False
print(s.upper(), s.lower(), s.title(), s.replace("fun", "great"))
print(s.find("is"), s.find("xyz"), s.count("n")) # 7 -1 2 - find returns -1 when missing
print(" padded ".strip() + "|") # padded|
print("a,b,c".split(","), "-".join(["2026", "10", "30"])) # ['a', 'b', 'c'] 2026-10-30
print("ha" * 3, "abc" + "def") # hahaha abcdef
print("line1\nline2\ttabbed") # \n is a new line, \t a tab
print(r"C:\new\table") # C:\new\table - a raw string keeps backslashes (good for Windows paths and regular expressions)
The slice s[start:stop] includes start and excludes stop. This “half-open” rule makes ranges easy to combine: s[:3] + s[3:] is always the whole string.
f-strings: the modern way to build text
name, price, qty = "Tea", 3.5, 4
print(f"{name} costs {price} each") # Tea costs 3.5 each
print(f"Total: {price * qty:.2f} USD") # Total: 14.00 USD - :.2f = two decimals
print(f"{1234567.891:,.1f}") # 1,234,567.9 - thousands separator
print(f"{42:05d} | {'left':<8} | {'right':>8} | {0.256:.1%}") # 00042 | left | right | 25.6%
print(f"{name=}") # name='Tea' - handy for debugging
text = """A multi-line
string keeps its line breaks."""
print(text.splitlines()) # ['A multi-line', 'string keeps its line breaks.']
Python 3 strings are Unicode, so accents, Arabic and emoji just work. When you must work with raw bytes (network data, binary files), use bytes: "é".encode("utf-8") gives b'\xc3\xa9', and .decode("utf-8") reverses it. Always state the encoding when you read or write text files.
4. Collections: lists, tuples, dictionaries and sets
| Type | Example | Ordered? | Changeable? | Use it for |
|---|---|---|---|---|
list |
[1, 2, 3] |
Yes | Yes | A sequence you add to and change |
tuple |
(1, 2, 3) |
Yes | No | A fixed group of values (a point, a record) |
dict |
{"a": 1} |
Yes (insertion order) | Yes | Look things up by a key |
set |
{1, 2, 3} |
No | Yes | Unique items and fast “is it in here?” |
Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # add at the end
fruits.insert(1, "avocado") # insert at a position
fruits.remove("banana") # remove by value
last = fruits.pop() # remove and return the last item
print(fruits, last) # ['apple', 'avocado', 'cherry'] date
print(fruits[0], fruits[-1], fruits[1:], len(fruits)) # apple cherry ['avocado', 'cherry'] 3
print("cherry" in fruits, fruits.index("cherry")) # True 2
numbers = [5, 2, 9, 1]
print(sorted(numbers), numbers) # [1, 2, 5, 9] [5, 2, 9, 1] - sorted() returns a new list
numbers.sort(reverse=True) # sort() changes the list itself
print(numbers) # [9, 5, 2, 1]
a = [1, 2, 3]
b = a # NOT a copy: both names point to the same list
b.append(4)
print(a) # [1, 2, 3, 4]
c = a.copy() # a real (shallow) copy; a[:] and list(a) do the same
c.append(5)
print(a, c) # [1, 2, 3, 4] [1, 2, 3, 4, 5]
Remember: b = a never copies. It gives the same object a second name. This surprises almost every beginner once.
Tuples and unpacking
point = (3, 4)
x, y = point # unpacking
print(x, y) # 3 4
first, *middle, last = [1, 2, 3, 4, 5] # * collects the rest
print(first, middle, last) # 1 [2, 3, 4] 5
def min_max(values):
return min(values), max(values) # returning a tuple lets a function return several values
low, high = min_max([4, 8, 1])
print(low, high) # 1 8
Dictionaries
person = {"name": "Sara", "age": 31}
person["city"] = "Tangier" # add or change a key
print(person["name"], person.get("phone"), person.get("phone", "none")) # Sara None none
print(list(person.keys()), list(person.values())) # ['name', 'age', 'city'] ['Sara', 31, 'Tangier']
for key, value in person.items():
print(key, "=", value) # name = Sara / age = 31 / city = Tangier
print("age" in person) # True: "in" checks the keys
del person["age"]
merged = person | {"role": "admin"} # merge dictionaries (Python 3.9+)
print(merged) # {'name': 'Sara', 'city': 'Tangier', 'role': 'admin'}
counts = {}
for word in "the cat and the dog and the bird".split():
counts[word] = counts.get(word, 0) + 1 # the classic counting pattern
print(counts) # {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
person["phone"] raises KeyError when the key is missing; person.get("phone") returns None instead. Dictionary lookups take the same short time however big the dictionary is, which makes dictionaries one of the most useful tools in the language.
Sets
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b, a & b, a - b, a ^ b) # {1, 2, 3, 4, 5} {3, 4} {1, 2} {1, 2, 5} - union, intersection, difference, in-one-only
print(len({1, 1, 2, 2, 3})) # 3: duplicates disappear
print(list(dict.fromkeys([3, 1, 3, 2, 1]))) # [3, 1, 2]: remove duplicates but keep the order
empty_set = set() # {} would create an empty dictionary
Comprehensions
A comprehension builds a collection from another in one readable line.
squares = [n * n for n in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [n for n in range(10) if n % 2 == 0] # [0, 2, 4, 6, 8]
lengths = {w: len(w) for w in ["pear", "fig", "apple"]} # {'pear': 4, 'fig': 3, 'apple': 5}
unique_lengths = {len(w) for w in ["pear", "fig", "apple", "plum"]} # {3, 4, 5}
pairs = [(x, y) for x in range(3) for y in range(2)] # nested loops
print(squares, evens, lengths, unique_lengths, pairs)
total = sum(n * n for n in range(1000)) # a generator expression: no list is built in memory
print(total) # 332833500
If a comprehension needs more than one condition and one loop, write a normal loop instead. Readability wins.
Looping tools
names = ["Ann", "Bob", "Cy"]
scores = [90, 72, 85]
for i, name in enumerate(names, start=1):
print(i, name) # 1 Ann / 2 Bob / 3 Cy
for name, score in zip(names, scores):
print(name, score) # Ann 90 / Bob 72 / Cy 85
print(dict(zip(names, scores))) # {'Ann': 90, 'Bob': 72, 'Cy': 85}
print(sorted(names, key=len, reverse=True), list(reversed(names))) # ['Ann', 'Bob', 'Cy'] ['Cy', 'Bob', 'Ann']
print(any(s > 80 for s in scores), all(s > 80 for s in scores)) # True False
5. Making decisions and repeating things
temperature = 22
if temperature > 30:
print("hot")
elif temperature > 18:
print("pleasant") # this runs
else:
print("cold")
print("warm" if temperature > 20 else "cool") # a one-line choice (conditional expression)
print(18 < temperature < 30) # True: comparisons can be chained
print(temperature > 20 and temperature < 25, not temperature == 22) # True False
Use == to compare values and is only to test for identity, mainly x is None. Combine tests with and, or, not. Python stops evaluating as soon as the answer is known (“short-circuit”), so if user and user.is_active: is safe even when user is None.
Loops
for i in range(3): # range(3) is 0, 1, 2
print("round", i)
for letter in "abc": # you can loop over any sequence
print(letter, end=" ") # a b c (end=" " stops the line break)
print()
n = 0
while n < 3:
n += 1 # x += 1 is the same as x = x + 1
print(n) # 3
for number in range(2, 20): # break, continue and the loop's else
if number % 2 == 0:
continue # skip to the next number
if number > 7:
break # leave the loop
print(number, end=" ") # 3 5 7
else:
print("never reached because of break")
print()
The else of a loop runs only when the loop was not ended by break. It is handy for searches: “if the loop finishes without finding it, then…”.
match: choosing between shapes of data (Python 3.10+)
def describe(command):
match command.split():
case ["quit"]:
return "bye"
case ["go", direction]:
return f"going {direction}"
case ["pick", *items] if items:
return f"picked {', '.join(items)}"
case _:
return "unknown"
print(describe("quit"), "|", describe("go north"), "|", describe("pick axe rope"), "|", describe("dance"))
# bye | going north | picked axe, rope | unknown
6. Functions
A function is a named, reusable block of code. It takes inputs (parameters) and gives back a result with return. Functions are how you avoid repeating yourself and how you split a big program into small, testable pieces.
def greet(name, greeting="Hello"):
"""Return a greeting. The text in triple quotes is the docstring: help(greet) shows it."""
return f"{greeting}, {name}!"
print(greet("Sara")) # Hello, Sara!
print(greet("Sara", "Salam")) # Salam, Sara!
print(greet(greeting="Hi", name="Omar")) # Hi, Omar! - keyword arguments can come in any order
def add(a, b):
return a + b
result = add(2, 3) # 5
print(result, greet.__doc__[:20]) # 5 Return a greeting. T
A function without a return returns None. Calling a function needs the parentheses: greet is the function, greet("x") runs it.
Flexible arguments
def total(*numbers): # *args collects extra positional arguments in a tuple
return sum(numbers)
def show(**options): # **kwargs collects extra keyword arguments in a dict
return options
def connect(host, port=5432, *, ssl=True): # parameters after * can only be passed by name
return f"{host}:{port} ssl={ssl}"
print(total(1, 2, 3, 4)) # 10
print(show(color="red", size=3)) # {'color': 'red', 'size': 3}
print(connect("db01", ssl=False)) # db01:5432 ssl=False
values = [1, 2, 3]
print(total(*values)) # 6 - * unpacks a list into arguments
settings = {"host": "db02", "port": 5433}
print(connect(**settings)) # db02:5433 ssl=True - ** unpacks a dict into keyword arguments
The mutable default trap
def add_item_wrong(item, bucket=[]): # the default list is created ONCE, when the function is defined
bucket.append(item)
return bucket
print(add_item_wrong("a"), add_item_wrong("b")) # ['a', 'b'] ['a', 'b'] - surprise: the same list is reused
def add_item(item, bucket=None): # the safe pattern
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item("a"), add_item("b")) # ['a'] ['b']
Never use a list, dictionary or set as a default value. Use None and create the object inside.
Scope, type hints and lambdas
counter = 0
def increase():
global counter # without this, "counter += 1" would create a new local variable
counter += 1
increase(); increase()
print(counter) # 2 (prefer passing values in and returning results instead of using global)
def average(values: list[float]) -> float: # type hints: documentation that tools such as mypy can check
return sum(values) / len(values)
print(average([1, 2, 3, 4])) # 2.5
square = lambda n: n * n # a small anonymous function: for one expression only
print(square(7)) # 49
people = [("Ann", 31), ("Bob", 25), ("Cy", 31)]
print(sorted(people, key=lambda p: (-p[1], p[0]))) # [('Ann', 31), ('Cy', 31), ('Bob', 25)]
print(list(map(str.upper, ["a", "b"])), list(filter(lambda n: n > 2, [1, 2, 3, 4]))) # ['A', 'B'] [3, 4]
Python looks up a name in this order: Local, Enclosing function, Global, Built-in. Reading a global from inside a function is fine; assigning to it needs global (or better, a different design). Type hints do not change how the program runs, but they make code easier to read, and editors use them for completion.
7. Closures, decorators and generators
Functions are values
You can store a function in a variable, pass it to another function, and return it. A function that remembers the variables around it is called a closure.
def make_multiplier(factor):
def multiply(n):
return n * factor # "factor" is remembered from the outer function
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10)) # 20 30
Decorators
A decorator wraps a function to add behaviour, such as timing, logging or access checks, without changing the function itself. The @name line above a function is shorthand for function = name(function).
import functools, time
def timed(func):
@functools.wraps(func) # keeps the original name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
@timed
def slow_sum(n):
return sum(range(n))
print(slow_sum(1_000_000)) # prints "slow_sum took 0.0xxxs" then 499999500000
Generators: values one at a time
A function that uses yield instead of return becomes a generator. It pauses at each yield and continues when asked for the next value, so it can produce huge or even endless sequences without storing them.
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3))) # [3, 2, 1]
def read_in_chunks(lines, size):
chunk = []
for line in lines:
chunk.append(line)
if len(chunk) == size:
yield chunk
chunk = []
if chunk:
yield chunk
print(list(read_in_chunks(["a", "b", "c", "d", "e"], 2))) # [['a', 'b'], ['c', 'd'], ['e']]
import itertools
def naturals():
n = 1
while True: # an endless sequence is fine for a generator
yield n
n += 1
print(list(itertools.islice(naturals(), 5))) # [1, 2, 3, 4, 5]
Generators are why you can process a 50 GB log file line by line with almost no memory: for line in open(path) reads lazily in the same way.
8. Errors and exceptions
When something goes wrong, Python raises an exception. If nothing handles it, the program stops and prints a traceback: read it from the bottom up, because the last line tells you what happened and the lines above show where.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("cannot divide by zero")
return None
except TypeError as error:
print("wrong types:", error)
return None
else:
return result # runs only if no exception happened
finally:
print("done") # ALWAYS runs: good for cleanup
print(divide(10, 4)) # done / 2.5
print(divide(1, 0)) # cannot divide by zero / done / None
print(divide("a", 1)) # wrong types: unsupported operand type(s) for /: 'str' and 'int' / done / None
Raising your own errors
class InsufficientFunds(Exception):
"""Raised when an account does not have enough money."""
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise InsufficientFunds(f"balance {balance} is less than {amount}")
return balance - amount
try:
withdraw(50, 80)
except InsufficientFunds as error:
print("Refused:", error) # Refused: balance 50 is less than 80
except ValueError as error:
print("Bad input:", error)
Rules for good error handling: catch specific exceptions, not a bare except: (which also hides typing mistakes and Ctrl+C); handle an error only where you can do something sensible about it; and never silently ignore errors. Use raise alone inside an except block to pass the error on, and raise NewError(...) from error to add context while keeping the original cause.
with: automatic cleanup
from contextlib import contextmanager
@contextmanager
def announce(task):
print("start", task)
try:
yield
finally:
print("end", task) # runs even if the block fails
with announce("backup"):
print("working...") # start backup / working... / end backup
The with statement guarantees that cleanup code runs: files are closed, locks released, database connections returned, whatever happens inside the block. You will use it constantly with files, next.
9. Files, paths, JSON and CSV
Use pathlib for paths. It works the same on Windows, Linux and macOS and is far nicer than joining strings. The examples below write into a temporary folder so you can run them safely.
from pathlib import Path
import tempfile
folder = Path(tempfile.mkdtemp()) # a new empty temporary folder
note = folder / "notes.txt" # the / operator joins path parts
print(note.name, note.suffix, note.parent == folder) # notes.txt .txt True
note.write_text("first line\nsecond line\n", encoding="utf-8")
print(note.read_text(encoding="utf-8").splitlines()) # ['first line', 'second line']
print(note.exists(), note.stat().st_size > 0) # True True (the exact size differs between Windows and Linux line endings)
with open(note, "a", encoding="utf-8") as f: # "a" = append, "w" = overwrite, "r" = read (default)
f.write("third line\n")
with open(note, encoding="utf-8") as f:
for line in f: # reads one line at a time: fine for huge files
print(line.rstrip()) # first line / second line / third line
(folder / "sub").mkdir()
for p in sorted(folder.rglob("*")): # rglob searches subfolders; glob() does one level
print(p.relative_to(folder)) # notes.txt / sub
JSON and CSV
import json, csv
data = {"name": "Sara", "skills": ["python", "sql"], "active": True, "manager": None}
json_file = folder / "profile.json"
json_file.write_text(json.dumps(data, indent=2), encoding="utf-8")
loaded = json.loads(json_file.read_text(encoding="utf-8"))
print(loaded["skills"], loaded == data) # ['python', 'sql'] True
print(json.dumps(data)) # {"name": "Sara", "skills": ["python", "sql"], "active": true, "manager": null}
csv_file = folder / "people.csv"
with open(csv_file, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows([{"name": "Ann", "age": 31}, {"name": "Bob", "age": 25}])
with open(csv_file, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print(rows) # [{'name': 'Ann', 'age': '31'}, {'name': 'Bob', 'age': '25'}] - CSV values are always text
print(sum(int(r["age"]) for r in rows)) # 56
Notice how JSON maps neatly onto Python: objects become dictionaries, arrays become lists, true and null become True and None. Always pass encoding="utf-8" when you open text files, because the default depends on the operating system and is the classic cause of “it works on my machine” bugs.
import os, shutil
print(os.environ.get("HOME", os.environ.get("USERPROFILE", "?")) != "") # True: environment variables
shutil.copy(note, folder / "notes-backup.txt") # copy a file
shutil.rmtree(folder) # delete a folder and everything in it: be careful with this one!
print(folder.exists()) # False
10. Modules, packages and pip
A module is just a .py file. A package is a folder of modules. You use them with import:
import math
from math import sqrt, pi
import random as rnd # a shorter alias
print(math.floor(2.7), sqrt(16), round(pi, 3)) # 2 4.0 3.142
# Typical project layout:
# myapp/
# __init__.py (can be empty: marks a package)
# utils.py -> from myapp.utils import slugify
# main.py
def main():
print("running as a program")
if __name__ == "__main__": # true only when this file is run directly, not when imported
main() # running as a program
The if __name__ == "__main__": guard lets a file be both a reusable module and a runnable script. Python searches for modules in the current folder, the installed packages and the standard library, so never name your own file after a standard module (a file called random.py will break import random).
Installing other people’s packages with pip
The Python Package Index (PyPI) has hundreds of thousands of free packages. Install them with pip, inside a virtual environment so that each project has its own set of packages. Our guide Python Virtual Environments Explained: venv and pip covers this in detail.
python -m venv .venv # create an environment in the folder .venv
.venv\Scripts\activate # Windows (Linux/macOS: source .venv/bin/activate)
python -m pip install requests # install a package
python -m pip install -r requirements.txt
python -m pip freeze > requirements.txt # record exact versions
python -m pip list --outdated
python -m pip uninstall requests
Always run pip as python -m pip: it guarantees you install into the Python you are actually using.
11. Classes and objects
Object-oriented programming bundles data and the functions that work on it into one unit. A class is the blueprint; an object (instance) is one thing built from it. Use a class when you have something with state and behaviour together: a bank account, a user, a connection.
class BankAccount:
bank_name = "Bigland Bank" # a class attribute: shared by all accounts
def __init__(self, owner, balance=0): # the constructor: runs when you create an object
self.owner = owner # instance attributes: each account has its own
self._balance = balance # a leading underscore means "internal, please don't touch"
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
@property
def balance(self): # read like an attribute: account.balance
return self._balance
def __str__(self): # what print() shows
return f"{self.owner}: {self._balance:.2f}"
def __repr__(self): # what the debugger and REPL show
return f"BankAccount({self.owner!r}, {self._balance})"
acc = BankAccount("Sara", 100)
acc.deposit(50)
acc.withdraw(30)
print(acc, acc.balance, acc.bank_name) # Sara: 120.00 120 Bigland Bank
print(repr(acc)) # BankAccount('Sara', 120)
self is the object the method is working on; Python passes it automatically as the first parameter. A @property lets you add validation or calculation later without changing how other code uses the class.
Inheritance and polymorphism
class SavingsAccount(BankAccount): # a SavingsAccount is a BankAccount, plus more
def __init__(self, owner, balance=0, rate=0.02):
super().__init__(owner, balance) # run the parent's constructor
self.rate = rate
def add_interest(self):
self.deposit(self._balance * self.rate)
def __str__(self): # override the parent's behaviour
return "Savings - " + super().__str__()
accounts = [BankAccount("Omar", 10), SavingsAccount("Lina", 1000, 0.05)]
for account in accounts:
print(account) # Omar: 10.00 / Savings - Lina: 1000.00
accounts[1].add_interest()
print(accounts[1].balance, isinstance(accounts[1], BankAccount)) # 1050.0 True
That loop shows polymorphism: the same call, print(account), does the right thing for each type of object. Python also uses duck typing: if an object has the methods you call, it works, whatever its class (“if it walks like a duck…”). Prefer composition (“has a”) over deep inheritance (“is a”): give a class the objects it needs instead of building tall class trees.
Special methods
class Money:
def __init__(self, cents):
self.cents = cents
def __add__(self, other): # makes + work
return Money(self.cents + other.cents)
def __eq__(self, other): # makes == work
return isinstance(other, Money) and self.cents == other.cents
def __lt__(self, other): # makes < work, so sorted() works too
return self.cents < other.cents
def __len__(self): # makes len() work
return len(str(self.cents))
def __repr__(self):
return f"Money({self.cents})"
print(Money(150) + Money(250), Money(5) == Money(5), sorted([Money(30), Money(10), Money(20)]), len(Money(12345)))
# Money(400) True [Money(10), Money(20), Money(30)] 5
dataclasses and enums
For classes that mostly hold data, a dataclass writes __init__, __repr__ and __eq__ for you:
from dataclasses import dataclass, field
from enum import Enum
class Priority(Enum):
LOW = 1
HIGH = 2
@dataclass
class Task:
title: str
priority: Priority = Priority.LOW
tags: list[str] = field(default_factory=list) # the safe way to have a list default
done: bool = False
t = Task("Write report", Priority.HIGH, ["work"])
print(t) # Task(title='Write report', priority=<Priority.HIGH: 2>, tags=['work'], done=False)
print(t == Task("Write report", Priority.HIGH, ["work"]), Priority.HIGH.name, Priority(1)) # True HIGH Priority.LOW
@dataclass(frozen=True, order=True) # frozen = immutable, order = comparable
class Version:
major: int
minor: int
print(Version(3, 12) > Version(3, 9)) # True
12. A tour of the standard library
Python’s motto is “batteries included”: the standard library solves many problems without installing anything. Before you reach for a package, check whether the standard library already does the job.
Dates and times
from datetime import datetime, date, timedelta, timezone
d = date(2026, 10, 30)
print(d.weekday(), d.strftime("%A %d %B %Y"), d + timedelta(days=45)) # 4 Friday 30 October 2026 2026-12-14
moment = datetime(2026, 10, 30, 14, 30, tzinfo=timezone.utc)
print(moment.isoformat(), moment.strftime("%H:%M")) # 2026-10-30T14:30:00+00:00 14:30
print(datetime.strptime("2026-12-25", "%Y-%m-%d").date() - d) # 56 days, 0:00:00
print((date(2026, 12, 25) - d).days) # 56
Store and compare times in UTC and convert to local time only when you display them. Use zoneinfo (ZoneInfo("Africa/Casablanca")) for time zones.
Regular expressions
import re
log = "2026-10-30 ERROR disk full on /dev/sda1; 2026-10-30 WARN cpu 91%"
print(re.findall(r"\d{4}-\d{2}-\d{2}", log)) # ['2026-10-30', '2026-10-30']
m = re.search(r"(?P<level>ERROR|WARN) (?P<msg>[^;]+)", log)
print(m.group("level"), "|", m.group("msg")) # ERROR | disk full on /dev/sda1
print(re.sub(r"\d+%", "N%", log)) # ... cpu N%
print(bool(re.fullmatch(r"[\w.+-]+@[\w-]+\.[\w.]+", "sara@example.com"))) # True
collections and itertools
from collections import Counter, defaultdict, deque, namedtuple
import itertools
print(Counter("mississippi").most_common(2)) # [('i', 4), ('s', 4)]
groups = defaultdict(list) # a dict that creates missing values for you
for word in ["apple", "avocado", "banana", "blueberry", "cherry"]:
groups[word[0]].append(word)
print(dict(groups)) # {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
queue = deque([1, 2, 3])
queue.appendleft(0); queue.pop()
print(queue) # deque([0, 1, 2])
Point = namedtuple("Point", "x y")
print(Point(3, 4).x) # 3
print(list(itertools.chain([1, 2], [3]) ), list(itertools.combinations("abc", 2)), list(itertools.permutations([1, 2, 3], 2))[:3])
# [1, 2, 3] [('a', 'b'), ('a', 'c'), ('b', 'c')] [(1, 2), (1, 3), (2, 1)]
print([(k, list(g)) for k, g in itertools.groupby("aabbbc")]) # [('a', ['a', 'a']), ('b', ['b', 'b', 'b']), ('c', ['c'])]
Random, math and statistics
import random, statistics
random.seed(42) # makes "random" numbers repeatable, handy in tests
print(random.randint(1, 6) in range(1, 7), random.choice(["a", "b"]) in "ab", len(random.sample(range(100), 5))) # True True 5
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(data), statistics.median(data), statistics.mode(data), round(statistics.stdev(data), 2)) # 5 4.5 4 2.14
import secrets
token = secrets.token_hex(8) # use secrets, not random, for passwords and tokens
print(len(token)) # 16
A command-line tool with argparse
import argparse
parser = argparse.ArgumentParser(description="Greet someone")
parser.add_argument("name", help="who to greet")
parser.add_argument("--times", type=int, default=1, help="how many times")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args(["Sara", "--times", "2", "-v"]) # normally: parser.parse_args() reads the real command line
for _ in range(args.times):
print("Hello", args.name) # Hello Sara (twice)
print(args.verbose) # True
Run a real script as python greet.py Sara --times 2, and python greet.py -h prints automatic help. For anything that others will run, argparse is better than reading sys.argv by hand.
Logging instead of print
import logging, io
stream = io.StringIO() # in a real program you would log to a file or the console
logging.basicConfig(stream=stream, level=logging.INFO, format="%(levelname)s %(name)s: %(message)s", force=True)
log = logging.getLogger("backup")
log.info("started")
log.warning("disk at %d%%", 91)
log.debug("not shown: below INFO")
print(stream.getvalue().strip().splitlines()) # ['INFO backup: started', 'WARNING backup: disk at 91%']
Logging gives you severity levels, timestamps, destinations and the ability to turn detail up or down without editing code. Use it for anything that runs unattended.
Running other programs
import subprocess, sys
result = subprocess.run([sys.executable, "-c", "print('from a child process')"], capture_output=True, text=True, check=True)
print(result.stdout.strip(), result.returncode) # from a child process 0
Pass the command as a list, not one long string, and avoid shell=True with user input: it opens the door to command injection. check=True raises an error if the program fails.
sqlite3: a database in the standard library
import sqlite3
db = sqlite3.connect(":memory:") # or a file name such as "app.db"
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
db.executemany("INSERT INTO users (name, age) VALUES (?, ?)", [("Ann", 31), ("Bob", 25), ("Cy", 40)])
db.commit()
for row in db.execute("SELECT name, age FROM users WHERE age > ? ORDER BY age DESC", (28,)):
print(row) # ('Cy', 40) / ('Ann', 31)
db.close()
The question marks are parameters. Never build SQL by gluing strings together with user input (that is SQL injection); always pass values separately, as above. The same pattern works with PostgreSQL, MySQL and SQL Server drivers. For SQL itself, see our SQL Server cheat sheet and Oracle guide.
Doing several things at once
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay) # a stand-in for a network request
return f"{name} done"
async def main():
results = await asyncio.gather(fetch("a", 0.2), fetch("b", 0.1), fetch("c", 0.15))
return results
print(asyncio.run(main())) # ['a done', 'b done', 'c done'] - in about 0.2 s, not 0.45 s
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=3) as pool:
print(list(pool.map(lambda n: n * n, range(5)))) # [0, 1, 4, 9, 16]
Use asyncio (or threads) for work that waits, such as network calls and disk reads. For heavy calculations on several CPU cores, use multiprocessing or ProcessPoolExecutor, because Python’s global interpreter lock lets only one thread run Python code at a time in the standard build.
Downloading from the web (needs the requests package)
import requests # python -m pip install requests
response = requests.get("https://api.github.com/repos/python/cpython", timeout=10)
response.raise_for_status() # raises an error for 4xx and 5xx answers
data = response.json()
print(data["stargazers_count"])
Always set a timeout; without one a stuck server can hang your program forever. The standard library has urllib.request if you cannot install packages.
13. Testing your code
A test is code that checks that other code does what you expect. Tests let you change code without fear. The simplest test is an assert; the standard library includes unittest; and most projects use the free pytest package.
def slugify(title):
"""'Hello, World!' -> 'hello-world'"""
import re
words = re.findall(r"[a-z0-9]+", title.lower())
return "-".join(words)
assert slugify("Hello, World!") == "hello-world" # fails with AssertionError if false
import unittest
class SlugifyTests(unittest.TestCase):
def test_basic(self):
self.assertEqual(slugify("Python 3 Tutorial"), "python-3-tutorial")
def test_extra_symbols(self):
self.assertEqual(slugify(" --A & B-- "), "a-b")
def test_empty(self):
self.assertEqual(slugify(""), "")
def test_error(self):
with self.assertRaises(AttributeError):
slugify(None)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(SlugifyTests)
import io
outcome = unittest.TextTestRunner(verbosity=0, stream=io.StringIO()).run(suite) # stream=... keeps the report quiet here
print(outcome.testsRun, outcome.wasSuccessful()) # 4 True
In a real project you put tests in files named test_*.py and run python -m unittest. With pytest the same tests are plain functions with plain assert statements, and you run pytest:
# test_slug.py
from myapp.text import slugify
def test_basic():
assert slugify("Python 3 Tutorial") == "python-3-tutorial"
import pytest
@pytest.mark.parametrize("title, expected", [("A b", "a-b"), (" X ", "x"), ("", "")])
def test_many(title, expected):
assert slugify(title) == expected
Good tests are small, check one thing, run fast and do not depend on each other. Write a test first when you find a bug: it proves the bug exists and proves your fix works.
14. Writing good Python
- Follow PEP 8, the official style guide: four-space indentation,
snake_casenames,CapWordsclasses, lines up to about 88 to 100 characters. Let a tool do it:blackformats code andrufffinds mistakes and style problems in milliseconds. - Be explicit and simple. “Readability counts” is in the Zen of Python (type
import this). Clear beats clever. - Use type hints on function signatures and check them with
mypyor your editor. - Keep functions short and focused on one job, with clear names. A function name should be a verb:
load_config, notconfig. - Use the right data structure. Membership tests belong in a set or dictionary, not a list.
- Prefer
pathlib, f-strings,with, comprehensions and the standard library over hand-made versions. - Use virtual environments for every project and keep a
requirements.txtorpyproject.toml. - Measure before you optimise:
timeitfor a snippet,cProfilefor a program. Most slow Python code is slow because of the algorithm, not the language (see our algorithms tutorial).
Mistakes everybody makes once
numbers = [2, 4, 6, 7]
for n in numbers: # WRONG: changing a list while looping over it skips items
if n % 2 == 0:
numbers.remove(n)
print(numbers) # [4, 7] - the 4 survived! Python moved on to the next position after the list shrank
numbers = [2, 4, 6, 7]
numbers = [n for n in numbers if n % 2 != 0] # the fix: build a new list
print(numbers) # [7]
print([] == [], [] is []) # True False: == compares values, "is" compares identity
print(0.1 * 3 == 0.3) # False: do not compare floats with ==
funcs = [lambda: i for i in range(3)] # late binding: all three see the final value of i
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)] # fix: capture the value as a default argument
print([f() for f in funcs]) # [0, 1, 2]
text = ""
for part in ["a", "b", "c"]:
text += part # fine for small loops; for thousands of parts use "".join(parts)
print(text, "".join(["a", "b", "c"])) # abc abc
15. Two small projects
Real learning happens when you combine the pieces. Here are two complete programs. Type them in, run them, then extend them.
Project 1: a word-frequency report
This reads text, ignores common words, counts the rest and prints a ranked report. It uses functions, regular expressions, Counter, sorting and f-strings.
import re
from collections import Counter
STOP_WORDS = {"the", "a", "an", "and", "or", "of", "to", "in", "is", "it", "that", "for"}
def count_words(text, top=3):
words = re.findall(r"[a-z']+", text.lower())
meaningful = [w for w in words if w not in STOP_WORDS and len(w) > 2]
return Counter(meaningful).most_common(top)
def report(text, top=3):
lines = []
for rank, (word, count) in enumerate(count_words(text, top), start=1):
lines.append(f"{rank}. {word:<10} {'#' * count} ({count})")
return "\n".join(lines)
sample = """Python is easy to learn. Python is also powerful: Python scripts automate the
boring work, and the standard library is huge. Learn Python, then learn more Python."""
print(report(sample))
# 1. python ##### (5)
# 2. learn ### (3)
# 3. easy # (1) - words with the same count keep the order in which they first appeared
Project 2: a command-line to-do list that saves to a file
This one uses classes, JSON files, error handling and argparse: the building blocks of most small tools. The commands are add, list, done and remove.
import argparse, json
from dataclasses import dataclass, asdict
from pathlib import Path
@dataclass
class Item:
title: str
done: bool = False
class TodoList:
def __init__(self, path):
self.path = Path(path)
self.items = self._load()
def _load(self):
if not self.path.exists():
return []
return [Item(**raw) for raw in json.loads(self.path.read_text(encoding="utf-8"))]
def _save(self):
self.path.write_text(json.dumps([asdict(i) for i in self.items], indent=2), encoding="utf-8")
def add(self, title):
self.items.append(Item(title))
self._save()
def complete(self, number):
self._get(number).done = True
self._save()
def remove(self, number):
self.items.remove(self._get(number))
self._save()
def _get(self, number):
if not 1 <= number <= len(self.items):
raise IndexError(f"no task number {number}")
return self.items[number - 1]
def lines(self):
return [f"{n}. [{'x' if i.done else ' '}] {i.title}" for n, i in enumerate(self.items, start=1)]
def main(argv=None, path="todo.json"):
parser = argparse.ArgumentParser(description="A tiny to-do list")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("list")
sub.add_parser("add").add_argument("title")
sub.add_parser("done").add_argument("number", type=int)
sub.add_parser("remove").add_argument("number", type=int)
args = parser.parse_args(argv)
todo = TodoList(path)
try:
if args.command == "add":
todo.add(args.title)
elif args.command == "done":
todo.complete(args.number)
elif args.command == "remove":
todo.remove(args.number)
except IndexError as error:
print("Error:", error)
return 1
print("\n".join(todo.lines()) or "(nothing to do)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Save it as todo.py and try python todo.py add "Learn Python", python todo.py list, python todo.py done 1. Here is the same program driven from code, to show the result:
import tempfile, os
path = os.path.join(tempfile.mkdtemp(), "todo.json")
main(["add", "Learn Python"], path) # 1. [ ] Learn Python
main(["add", "Build a project"], path) # 1. [ ] Learn Python
# 2. [ ] Build a project
main(["done", "1"], path) # 1. [x] Learn Python
# 2. [ ] Build a project
main(["done", "9"], path) # Error: no task number 9
Extend it: add due dates and sorting, a --priority option, a nicer table with colours, tests with unittest, or turn it into a web app with Flask.
16. Where to go next, and FAQ
A practice plan
- Week 1: sections 1 to 5. Solve 20 small exercises (FizzBuzz, reverse a string, count vowels, a guessing game, a temperature converter).
- Week 2: sections 6 to 9. Write a script that organises the files in a folder by extension; a script that reads a CSV and prints totals.
- Week 3: sections 10 to 12. Build the to-do list, then your own small tool that solves a problem you really have.
- Week 4: section 13 and 14, then pick a direction below and build one project in it.
Directions
| You want to… | Learn |
|---|---|
| Automate system administration | pathlib, subprocess, paramiko or fabric for SSH, psutil; compare with PowerShell and the Linux commands |
| Build websites and APIs | Flask or FastAPI (small, quick), Django (batteries included) |
| Analyse data | pandas, numpy, matplotlib, Jupyter notebooks |
| Work with databases | sqlite3, SQLAlchemy, drivers for PostgreSQL, MySQL, SQL Server |
| Machine learning | scikit-learn, then PyTorch or TensorFlow |
| Get better at problem solving | Our algorithms tutorial, LeetCode, Advent of Code |
Quick answers
Is Python slow? Python is slower than C or Java for pure number crunching, but it rarely matters: most programs wait for disks, networks and databases, and the heavy libraries (numpy, pandas) are written in C. Choose a good algorithm first, measure, and only then optimise.
Python 2 or 3? Always 3. Python 2 stopped receiving updates in 2020.
Which version should I install? The latest stable release, or whatever your servers use, so your code behaves the same everywhere. Check python --version, and use a virtual environment per project.
How do I learn faster? Write code every day, even 20 minutes. Read other people’s code. Build things you care about. When you are stuck, read the error message from the bottom up, search for the exact message, and make the problem smaller until you can explain it in one sentence. The official documentation at docs.python.org (especially the Tutorial and the Library Reference) is excellent and free.
What next on this site? Browse the Python category for focused guides, such as virtual environments, and see the free online tools for formatters and converters you will use while coding.
More tutorials like this
Algorithms Tutorial: Big O, Sorting, Graphs and Dynamic Programming in Python
A full algorithms tutorial for beginners: Big O, searching, sorting, recursion, hashing patterns, trees, graphs (BFS, DFS, Dijkstra), greedy methods and dynamic programming, with…
Python Virtual Environments Explained: venv and pip
Stop breaking your Python projects. Create an isolated environment with venv, install packages with pip, save them to requirements.txt and rebuild anywhere.


