From installing Python through syntax, data structures, comprehensions/generators, decorators, context managers, advanced type hints, concurrency (threading/multiprocessing/asyncio), package management (uv), and testing — everything from first steps to a practical intermediate level, in one place.
Beginner
Updated Oct 1, 2026
~12 min read
19 sections
20 code examples
Web IDE lab included
🐍
Python Basics Web IDE
Run code in the browser with nothing to install and learn through step-by-step examples.
Understanding Python Basics as a real-world workflow
From installing Python through syntax, data structures, comprehensions/generators, decorators, context managers, advanced type hints, concurrency (threading/multiprocessing/asyncio), package management (uv), and testing — everything from first steps to a practical intermediate level, in one place. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Backend / systems development
Before syntax, pin down the boundaries a request crosses: validation, processing, storage, and response.
From Python beginner to intermediateConcurrency fundamentalsPackage management with uvPractical testing with pytest
Architecture diagrams
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Python Basics.
Learning flow
Rendering diagram…
Architecture view
Rendering diagram…
Installation & runtime environment
When you first open Python Basics, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
With Python, the norm is a separate virtual environment per project rather than using the interpreter installed system-wide. At first, installing from python.org and using venv is enough, and once you start handling several projects it is better to manage dependencies and lock files with uv.
BASH
# Check the versionpython --version# Create a projectmkdir python-basic && cd python-basicpython -m venv .venv# macOS/Linuxsource .venv/bin/activate# Windows PowerShell.venv\Scripts\Activate.ps1# Install packagespython -m pip install --upgrade pippython -m pip install requests pytest
Variables and basic syntax
Here you look at Variables and basic syntax alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Python delimits blocks by indentation, and variables do not need a declared type. In intermediate and more advanced code, though, it is good to use type hints as well, to improve IDE autocompletion, reviews, and test quality.
For money calculations, consider Decimal instead of float.
Conditionals
`if / elif / else`
Move complex conditions into functions.
Loops
`for`, `while`
Use enumerate when you need the index.
Data structures
Here you look at Data structures alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Productivity in Python comes from handling list, tuple, dict, and set naturally. Deciding first whether the data needs order, whether duplicates are allowed, and whether key-based lookup is needed leads you to the right data structure.
collections_demo.pyPYTHON
users = [ {"id": 1, "name": "Ada", "role": "admin"}, {"id": 2, "name": "Linus", "role": "developer"}, {"id": 3, "name": "Grace", "role": "developer"},]names = [user["name"] for user in users]developers = [u for u in users if u["role"] == "developer"]user_by_id = {user["id"]: user for user in users}roles = {user["role"] for user in users}print(names)print(user_by_id[2]["name"])print(sorted(roles))
Data structure
Traits
Typical uses
list
Ordered, duplicates allowed
Lists, sorting, filtering
tuple
Immutable
Coordinates, fixed return values
dict
Key-value lookup
Settings, indexes, JSON-shaped data
set
Removes duplicates
Tags, permissions, intersection/difference
Comprehensions & generators
Here you look at Comprehensions & generators alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
A comprehension is syntax that compresses a loop into one line, and a generator produces results lazily, only as many as needed, instead of loading them all into memory at once (lazy evaluation). When handling large volumes of data, using a generator instead of a list cuts memory use considerably.
generators_demo.pyPYTHON
# list/dict/set comprehensions — build the whole thing in memory immediatelysquares = [n * n for n in range(10)]even_squares = {n: n * n for n in range(10) if n % 2 == 0}# Generator function — returns one value at each yield and pausesdef read_large_file(path: str): with open(path, encoding="utf-8") as f: for line in f: yield line.strip()# Generator expression — using () instead of [] makes it lazytotal = sum(n * n for n in range(1_000_000)) # sums on the fly without building a list# Handling infinite/large streams with itertoolsfrom itertools import islicedef counter(): n = 0 while True: yield n n += 1first_five = list(islice(counter(), 5))print(first_five)
Kind
When evaluated
Memory
Re-iteration
List comprehension `[...]`
Builds everything immediately
As much as the whole data
Any number of times
Generator expression `(...)`
Produces one value each time one is requested
Only one item at a time
One-shot (cannot be reused once exhausted)
Functions and type hints
Here you look at Functions and type hints alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The function is the most important unit of separation in Python code. Stating the input and output types lets even a small script grow into a maintainable module.
functions.pyPYTHON
from dataclasses import dataclass@dataclassclass Order: id: int amount: float paid: bool = Falsedef total_paid(orders: list[Order]) -> float: return sum(order.amount for order in orders if order.paid)def normalize_name(value: str) -> str: return value.strip().title()orders = [Order(1, 12000, True), Order(2, 8000, False)]print(total_paid(orders))
Decorators
Here you look at Decorators alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
A decorator is syntax that wraps a function to slot in common logic (logging, caching, permission checks, retries) before and after it runs. Do not forget to preserve the name and docstring of the original function with `functools.wraps`.
decorators.pyPYTHON
import timeimport functoolsdef retry(times: int = 3): """A decorator that takes arguments is a factory that wraps the function one level further.""" def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): last_error: Exception | None = None for attempt in range(1, times + 1): try: return func(*args, **kwargs) except Exception as exc: last_error = exc print(f"[retry {attempt}/{times}] {func.__name__} failed: {exc}") raise last_error return wrapper return decorator@retry(times=3)def call_flaky_api() -> str: if time.time() % 2 < 1: raise ConnectionError("Temporary network error") return "ok"# Built-in decoratorsclass Circle: def __init__(self, radius: float) -> None: self._radius = radius @property def area(self) -> float: return 3.14159 * self._radius ** 2 @staticmethod def unit() -> "Circle": return Circle(1)@functools.lru_cache(maxsize=None)def fibonacci(n: int) -> int: return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)
Decorator
Use
`@property`
Makes a method accessible like an attribute (getter)
`@staticmethod`
A function with no self that only borrows the class namespace
`@classmethod`
Receives the class itself (cls) as the first argument — alternative constructors and so on
`@functools.lru_cache`
Caches the results of calls with the same arguments to avoid recomputation
`@functools.wraps`
Preserves the metadata of the original function inside a custom decorator
Modules and packages
Here you look at Modules and packages alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
When a single file grows large, split it into modules by feature. Clear import paths make testing and deployment easier, and it is a good habit to put the execution entry point under `if __name__ == "__main__"`.
Here you look at File I/O alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
When working with files you need to think about encoding, paths, and exception handling together. Default to UTF-8 for text, and build paths with pathlib to reduce differences between operating systems.
files.pyPYTHON
from pathlib import Pathimport jsondata_dir = Path("data")data_dir.mkdir(exist_ok=True)users = [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Linus"}]path = data_dir / "users.json"path.write_text(json.dumps(users, ensure_ascii=False, indent=2), encoding="utf-8")loaded = json.loads(path.read_text(encoding="utf-8"))for user in loaded: print(user["id"], user["name"])
Context managers & resource management
Here you look at Context managers & resource management alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The `with` statement safely releases resources that must be cleaned up, such as files, network connections, and locks, even when an exception occurs. You can implement `__enter__`/`__exit__` yourself, or create one simply from a single generator function with `contextlib.contextmanager`.
context_managers.pyPYTHON
import timefrom contextlib import contextmanager# 1) Class-based context managerclass Timer: def __enter__(self): self._start = time.perf_counter() return self def __exit__(self, exc_type, exc_value, traceback): elapsed = time.perf_counter() - self._start print(f"Elapsed: {elapsed:.3f}s") return False # do not swallow the exception; let it propagatewith Timer(): time.sleep(0.1)# 2) Generator-based context manager — the same job in far less code@contextmanagerdef timer(): start = time.perf_counter() try: yield finally: print(f"Elapsed: {time.perf_counter() - start:.3f}s")with timer(): time.sleep(0.1)# 3) Cleaning up several resources at oncewith open("in.txt", encoding="utf-8") as src, open("out.txt", "w", encoding="utf-8") as dst: dst.write(src.read().upper())
Exception handling
Here you look at Exception handling alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Exception handling is not a tool for hiding errors but a device for expressing failure clearly. An except that is too broad hides problems, so catch only the exceptions you can anticipate and pass a meaningful message to the caller.
errors.pyPYTHON
from pathlib import Pathdef read_config(path: str) -> dict[str, str]: file = Path(path) if not file.exists(): raise FileNotFoundError(f"config not found: {path}") result: dict[str, str] = {} for line in file.read_text(encoding="utf-8").splitlines(): if not line.strip() or line.startswith("#"): continue key, value = line.split("=", 1) result[key.strip()] = value.strip() return resulttry: config = read_config("app.env")except FileNotFoundError as exc: print(f"Configuration error: {exc}")
Classes and object orientation
Here you look at Classes and object orientation alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
In Python, use a class when state and behavior need to be bundled together. A dataclass is enough for plain data, and favoring composition and small objects over complex inheritance is better for maintainability.
oop.pyPYTHON
from dataclasses import dataclass@dataclassclass Account: owner: str balance: int = 0 def deposit(self, amount: int) -> None: if amount <= 0: raise ValueError("amount must be positive") self.balance += amount def withdraw(self, amount: int) -> None: if amount > self.balance: raise ValueError("insufficient balance") self.balance -= amountaccount = Account("Ada")account.deposit(10000)account.withdraw(3000)print(account.balance)
Advanced type hints
Here you look at Advanced type hints alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Beyond the simple type hints covered in the basic syntax, the tools of the `typing` module let you express more precise contracts. Hooking a static type checker such as mypy or pyright into CI catches type errors ahead of time, without running the code.
typing_advanced.pyPYTHON
from typing import TypedDict, Protocol, Literal# State that a value may be absent (in Python 3.10+, str | None instead of Optional[str])def find_user(user_id: int) -> str | None: return "Ada" if user_id == 1 else None# One of several typesdef parse_amount(value: int | str) -> float: return float(value)# A dict type with a fixed structure, like JSONclass UserPayload(TypedDict): id: int name: str role: Literal["admin", "developer", "viewer"]def greet(user: UserPayload) -> str: return f"Welcome, {user['name']} ({user['role']})"# Structural typing: "having this method is enough", with no inheritanceclass SupportsTotal(Protocol): def total(self) -> float: ...def print_total(item: SupportsTotal) -> None: print(f"Total: {item.total()}")
Tool
Use
`X | None` (`Optional[X]`)
States that a value may be absent
`A | B` (`Union[A, B]`)
Allows one of several types
`TypedDict`
States the key and value types of a dict, like a JSON struct
`Protocol`
Structural typing that only requires the needed methods, with no inheritance
`Literal["a", "b"]`
Restricts to one of a fixed set of values
Using the standard library
Here you look at Using the standard library alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The Python standard library is the basic toolkit for automation and data processing. Knowing just datetime, pathlib, json, csv, argparse, and logging is enough to build small operational scripts reliably.
report.pyPYTHON
import argparseimport csvimport loggingfrom pathlib import Pathlogging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")parser = argparse.ArgumentParser()parser.add_argument("--file", default="orders.csv")args = parser.parse_args()path = Path(args.file)total = 0with path.open(encoding="utf-8", newline="") as f: for row in csv.DictReader(f): total += int(row["amount"])logging.info("total amount: %s", total)
Here you look at Concurrency basics (threading/multiprocessing/asyncio) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Because of the GIL (Global Interpreter Lock), Python cannot have several threads executing Python bytecode at the same time within one process. So the tool has to be chosen according to "what is being waited on right now" — asyncio or threading for work that waits on I/O, and multiprocessing for CPU-heavy computation.
concurrency_demo.pyPYTHON
import asyncioimport timefrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor# I/O bound: wait in several threads at oncedef download(url: str) -> str: time.sleep(0.5) # simulates waiting on the network return f"downloaded: {url}"with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(download, ["a.com", "b.com", "c.com"]))# CPU bound: true parallel computation across several processesdef heavy_square(n: int) -> int: return sum(i * i for i in range(n))with ProcessPoolExecutor(max_workers=4) as pool: results = list(pool.map(heavy_square, [10_000_000] * 4))# asyncio: handle a great many waits at once in a single threadasync def fetch(session_id: int) -> str: await asyncio.sleep(0.5) # must be the asyncio sleep — time.sleep stalls the event loop return f"session {session_id} done"async def main() -> None: results = await asyncio.gather(*(fetch(i) for i in range(10))) print(results)asyncio.run(main())
Situation
Suitable tool
Why
Making many network requests at once (I/O bound)
asyncio
Waits on thousands at once in a single thread, with the lowest context switching cost
File/DB I/O with existing synchronous libraries
threading
The GIL is released while waiting on I/O, so several threads can wait at the same time
Image processing, numeric computation (CPU bound)
multiprocessing
Each process has its own interpreter and GIL, giving true parallel execution
Advanced package management (uv)
Here you look at Advanced package management (uv) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
If you started with just venv + pip, then as the project grows you come to need reproducible dependency locking and a standardized build. `pyproject.toml` is now the standard configuration file replacing `setup.py`, and `uv` builds on it to unify dependency installation, virtual environments, and lock management in a single, very fast CLI.
# Initialize a project (creates the venv + pyproject.toml automatically)uv init python-basic && cd python-basic# Add a dependency (installs + updates pyproject.toml + uv.lock together)uv add requestsuv add --dev pytest# Reproduce exactly the same environment from the lockuv sync# Run directly in the locked environment without activating the venv yourselfuv run python -m app.cliuv run pytest
Tool
Characteristics
pip + requirements.txt
The simplest, but with no proper lock file (imitated with pip freeze)
pip-tools
Generates a lock file from requirements.in → requirements.txt
Poetry
pyproject.toml based; integrates the lock file with build and publishing
uv
Written in Rust and very fast; unifies venv, install, and lock in one CLI — spreading quickly as the new standard
Testing and project structure
Here you look at Testing and project structure alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The fastest way to raise your fundamentals to a practical level is to write tests alongside the code. Pinning down calculation logic, parsing logic, and exception cases with tests makes refactoring easier, and once you know fixtures and mocks you can safely verify code with external dependencies too.
import pytestfrom app.weather import WeatherClient@pytest.fixturedef client() -> WeatherClient: # A reusable piece of setup created fresh for each test return WeatherClient(api_key="test-key")def test_parses_temperature(client: WeatherClient, monkeypatch: pytest.MonkeyPatch): def fake_get(url: str) -> dict: return {"temp": 21.5} # Replace the real network call with a fake function monkeypatch.setattr(client, "_get", fake_get) assert client.current_temperature("Seoul") == 21.5
Concept
Role
`fixture`
Creates the setup each test needs (DB connections, objects) and handles the cleanup too
`monkeypatch` / `unittest.mock`
Replaces hard-to-control dependencies such as external APIs, time, and environment variables with fakes
`pytest.mark.parametrize`
Verifies the same logic repeatedly with several input values
`pytest --cov=app`
Shows the lines of code the tests do not cover, through coverage.py integration
Python Basics practical design
Python Basics practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
The Python Basics guide must not end at listing syntax. What matters is the flow that connects input handling, the choice of data structures, splitting into functions, the exception contract, and module structure, growing a small script into a maintainable program.
Decision point
Question to ask
Practical guideline
Boundaries
Which parts of the Python Basics code are most likely to change?
Separate input/output, configuration, external integrations, and the core rules.
State
Where is state created and where does it go away?
Make the owner and lifecycle of state visible in the code.
Failure
What does the caller receive on failure?
Decide the timeout, fallback, and error contract first.
Python Basics operating standards
This section covers Python Basics operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.
In practical use, stabilize the runtime environment, dependency versions, logs, configuration files, file paths, and encoding issues first. An automation script becomes an operational tool only when it also has a timeout, retries, and failure logs.
Python Basics verification strategy
Python Basics verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Applying function-level tests, exception cases, file I/O samples, type hints, and lint/format together carries you beyond learning basic syntax to practical code quality.
Quality axis
How to verify
Definition of done
Correctness
Automate the normal/failure cases.
The core scenarios pass reproducibly.
Regression prevention
When fixing a bug, leave the same case behind as a test.
The same failure is not deployed again.
Operability
Check the logs, metrics, and alerts.
There is a path for tracing the cause when a problem occurs.
Python Basics: frequently asked questions
Why do I need a Python virtual environment (venv)?
Each project needs different packages and versions. Installing everything globally means a package upgraded for one project can break another. Create an environment per project with python -m venv .venv, activate it, and install packages there so projects do not affect each other.
Should I use pip, conda, uv, or poetry?
pip and venv ship with Python and are enough for most projects. uv is compatible with pip, installs faster, and also manages Python versions. poetry is for managing dependency locking and package publishing with one tool. conda is mostly used in data science environments where libraries outside Python have to be installed too. If your team already uses a tool, follow it.
Why do I get ModuleNotFoundError and how do I fix it?
It most often happens when the Python that installed the package is not the Python running the code. Check that the virtual environment is activated, and install with python -m pip install package-name instead of pip so the package goes into the Python you are running. For your own modules, check the working directory, the package layout, and that the file name does not shadow a standard library module.
People say Python is slow. Can I use it for server development?
A web server spends most of its time waiting on databases and external APIs, so the raw speed of the language is rarely the bottleneck. Asynchronous frameworks combined with multiple processes give enough concurrency. For number-heavy work, use libraries implemented in C underneath, such as NumPy.