# PythonMates > Free, modern Python tutorials with code you can run in your browser, exercises, quizzes and real projects — from your first program to Python for AI. By Saurabh Jaiswal. Lessons are tested on Python 3.15. Each lesson opens with a short direct answer, then examples with their real output, an exercise with hints and a quiz. Author: Saurabh Jaiswal (https://saurabhjaiswal.com). ## Beginner: From zero to writing real programs: values, text, collections, decisions, loops, functions and files. - [What is Python?](https://pythonmates.com/learn/beginner/what-is-python/): Python is a free, general-purpose programming language known for readable code that looks close to plain English. It runs everywhere — from scripts on your laptop to web apps and the AI systems behind ChatGPT-style tools — which makes it the most widely taught first language today. - [Your first program](https://pythonmates.com/learn/beginner/first-program/): A Python program is a text file ending in .py that Python runs from top to bottom, one line at a time. The print() function shows output, # starts a comment that Python ignores, and you run a file with python hello.py. - [Variables](https://pythonmates.com/learn/beginner/variables/): A variable is a name that points to a value, created the first time you assign to it with = — for example age = 30. Python works out the type automatically, and you can point the same name at a new value at any time. - [Numbers](https://pythonmates.com/learn/beginner/numbers/): Python has whole numbers (int, like 42) and decimal numbers (float, like 3.14). You calculate with + - * /, use // for whole-number division, % for the remainder and ** for powers. Integers can be as large as you like. - [Strings](https://pythonmates.com/learn/beginner/strings/): A string (str) is text inside quotes, such as "hello". You can read characters by position (text[0]), cut pieces out with slices (text[0:5]) and use methods like .upper(), .strip() and .split(). Strings never change — methods return a new string. - [Lists](https://pythonmates.com/learn/beginner/lists/): A list is an ordered, changeable collection written with square brackets, like [3, 1, 2]. You read items by position (items[0]), add with .append(), remove with .remove() or .pop(), and sort with .sort() or sorted(). Lists can hold any type, even other lists. - [Tuples and sets](https://pythonmates.com/learn/beginner/tuples-and-sets/): A tuple is an ordered collection that can't be changed, written with round brackets: (52.5, 4.3). A set is an unordered collection of unique values, written with curly brackets: {"a", "b"}. Use tuples for fixed records and sets to remove duplicates or compare groups. - [Dictionaries](https://pythonmates.com/learn/beginner/dictionaries/): A dictionary (dict) stores key-value pairs, like {"name": "Asha", "age": 30}. You look values up by key (person["name"]), use .get() when a key might be missing, and loop over pairs with .items(). Dictionaries are how Python represents most real-world data, including JSON. - [Conditions](https://pythonmates.com/learn/beginner/conditions/): if runs a block of code only when a condition is True; elif checks another condition and else catches everything left. Conditions use comparisons such as ==, < and in, combined with and, or and not. Python uses indentation, not brackets, to mark each block. - [Loops](https://pythonmates.com/learn/beginner/loops/): A for loop repeats code once for each item in a collection: for name in names:. A while loop repeats as long as a condition stays true. Use range() for counting, enumerate() when you also need the position, zip() to walk two lists together, and break or continue to leave or skip. - [Functions](https://pythonmates.com/learn/beginner/functions/): A function is a named, reusable block of code. You define it with def name(parameters):, send results back with return, and call it with name(arguments). Functions keep code short, testable and easy to change, and type hints like def area(w: float, h: float) -> float: document what goes in and out. - [Files and errors](https://pythonmates.com/learn/beginner/files-and-errors/): Use with open("file.txt") as f: to read or write a file — with closes it for you, even if something goes wrong. Wrap code that can fail in try / except to handle the error instead of crashing, and use raise to report a problem yourself. ## Intermediate: Write Python like a professional: comprehensions, classes, modules, generators, decorators, typing and tests. - [Comprehensions](https://pythonmates.com/learn/intermediate/comprehensions/): A comprehension builds a new list, dict or set from another collection in one expression: [x * 2 for x in numbers if x > 0]. It reads as "give me this, for each item, if a condition holds". Use comprehensions for simple transforms and filters; switch to a normal loop when the logic needs more than one line. - [Lambda, map, filter and reduce](https://pythonmates.com/learn/intermediate/functional-tools/): A lambda is a small unnamed function written in one line: lambda x: x * 2. map() applies a function to every item, filter() keeps items where a function returns true, and reduce() combines items into one value. In modern Python, lambdas shine as the key for sorted(), min() and max(), while comprehensions usually replace map and filter. - [Classes and objects](https://pythonmates.com/learn/intermediate/classes/): A class is a blueprint that bundles data (attributes) and behaviour (methods); each object made from it is an instance. You define one with class Name:, set up its data in __init__(self, ...), and reach that data through self. Classes are worth it when several functions keep working on the same piece of data. - [Dataclasses](https://pythonmates.com/learn/intermediate/dataclasses/): @dataclass turns a class with type-annotated fields into a full data container: Python writes __init__, __repr__ and __eq__ for you. Use it whenever a class mainly holds data, such as a product, an order or a config. Options like frozen=True and order=True add immutability and sorting. - [Modules, packages and environments](https://pythonmates.com/learn/intermediate/modules-and-packages/): A module is any .py file; a package is a folder of modules. You reuse code with import. Third-party packages are installed from PyPI into a virtual environment — a private folder of packages for one project — with pip or the faster uv, and listed in pyproject.toml so anyone can recreate the setup. - [Iterators and generators](https://pythonmates.com/learn/intermediate/iterators-and-generators/): An iterator hands out values one at a time with next() until it raises StopIteration; every for loop uses one behind the scenes. A generator is the easy way to write your own iterator: a function that uses yield instead of return. Generators are lazy, so they can process huge files or endless streams with almost no memory. - [Decorators](https://pythonmates.com/learn/intermediate/decorators/): A decorator is a function that takes another function and returns an improved version of it. Writing @timer above def work(): is short for work = timer(work). Decorators add behaviour such as logging, timing, retries or caching without touching the function's own code. - [Type hints](https://pythonmates.com/learn/intermediate/type-hints/): Type hints describe what types a variable, parameter or return value should have, like def total(prices: list[float]) -> float:. Python doesn't enforce them while running; instead your editor, type checkers such as mypy, and AI coding assistants use them to catch mistakes early and understand your code. - [Testing with pytest](https://pythonmates.com/learn/intermediate/testing-with-pytest/): A test is a small function that runs your code and checks the result with assert. pytest finds every function named test_* in files named test_*.py, runs them and reports what failed and why. Tests let you change code — or accept code from an AI assistant — with confidence. - [Project: build a dodge game with pygame](https://pythonmates.com/learn/intermediate/pygame-game/): A pygame game is a loop that runs about 60 times a second: read input, update positions, check collisions, then draw the frame. In this project you build Dodge — move a player left and right to avoid falling blocks — in about 100 lines, using classes, functions and everything else from the Intermediate path. ## Advanced: Concurrency, parallelism and performance: threads, processes, async/await, sockets and packaging. - [Concurrency vs parallelism](https://pythonmates.com/learn/advanced/concurrency-vs-parallelism/): Concurrency means juggling several tasks so that waiting time is used for other work; parallelism means doing several things at literally the same moment on different CPU cores. In Python, use threads or asyncio for I/O-bound work (waiting on networks and files) and multiple processes for CPU-bound work (heavy calculations). - [Threads](https://pythonmates.com/learn/advanced/threads/): Threads let one Python program wait on many slow things at once, such as web requests or file downloads. The easiest and safest way is concurrent.futures.ThreadPoolExecutor: give it a function and a list of inputs, and it runs them across a pool of threads. Protect shared data with a Lock, or avoid sharing by returning results. - [Multiprocessing](https://pythonmates.com/learn/advanced/multiprocessing/): Multiprocessing runs work in several separate Python processes, each with its own interpreter and GIL, so CPU-heavy code really runs in parallel on several cores. Use concurrent.futures.ProcessPoolExecutor with map, keep the work in top-level functions, and always start pools under if __name__ == "__main__":. - [async and await](https://pythonmates.com/learn/advanced/async-await/): async def defines a coroutine — a function that can pause at each await while it waits for something, letting other coroutines run in the meantime. asyncio.run() starts the event loop, and asyncio.gather() or a TaskGroup runs many coroutines concurrently in a single thread. Async shines when a program handles hundreds or thousands of network connections. - [Sockets and networking](https://pythonmates.com/learn/advanced/sockets/): A socket is one end of a network connection. A server creates a socket, binds it to an address and port, listens and accepts connections; a client connects to that address and sends bytes. Python's socket module exposes this directly. For everyday web work you'll use libraries such as httpx or FastAPI, which are built on sockets. - [Performance and profiling](https://pythonmates.com/learn/advanced/performance/): First measure, then optimise: use timeit for small snippets and cProfile to find which functions take the time. The biggest wins usually come from better data structures (a set instead of a list for lookups), built-in functions, caching repeated work and moving number crunching to NumPy — not from clever tricks. - [Packaging and publishing](https://pythonmates.com/learn/advanced/packaging/): A Python package is described by a pyproject.toml file: name, version, dependencies and how to build it. uv build turns your project into a wheel (.whl) that anyone can install with pip install, and uv publish uploads it to PyPI. Entry points let users run your tool as a normal command. - [Project: speed up API calls](https://pythonmates.com/learn/advanced/speed-up-api-calls/): When a program calls many APIs one after another, almost all the time is spent waiting. Running the calls concurrently — with ThreadPoolExecutor for existing code or asyncio with httpx for new code — cuts the total to roughly the slowest call. Production versions add a concurrency limit, timeouts and retries. ## Python for AI: The Python behind modern AI: NumPy, pandas, charts, machine learning, LLM APIs, RAG and AI apps. - [NumPy essentials](https://pythonmates.com/learn/ai/numpy/): NumPy gives Python fast arrays of numbers. Instead of looping, you write maths on whole arrays at once — prices * 1.21 — and NumPy runs it in optimised C code. Almost every AI and data library, from pandas to PyTorch, is built on the same ideas: arrays, shapes, vectorised operations and broadcasting. - [pandas for data analysis](https://pythonmates.com/learn/ai/pandas/): pandas is Python's spreadsheet: a DataFrame is a table with named columns that you can load from CSV, Excel, SQL or JSON. You select columns with df["col"], filter rows with conditions, summarise with groupby, and clean missing values — the everyday work behind every data analysis and AI project. - [Charts with matplotlib](https://pythonmates.com/learn/ai/matplotlib/): matplotlib is Python's standard plotting library. Create a figure and axes with fig, ax = plt.subplots(), draw with ax.plot(), ax.bar() or ax.scatter(), label everything, then plt.show() or fig.savefig("chart.png"). pandas and most AI libraries use it for their built-in charts. - [Machine learning with scikit-learn](https://pythonmates.com/learn/ai/scikit-learn/): Machine learning means learning a rule from examples instead of writing it by hand. With scikit-learn the workflow is always the same: split data into training and test sets, fit a model on the training data, predict on the test data and measure how often it's right. Every model shares this fit / predict interface. - [Calling LLM APIs from Python](https://pythonmates.com/learn/ai/llm-apis/): You call an LLM by sending a list of messages to the provider's API — with their Python SDK — and reading the text that comes back. Keep the API key in an environment variable, give clear instructions in a system prompt, ask for structured JSON when code needs to use the answer, validate it with Pydantic, and always handle timeouts and retries. - [RAG basics: answer questions from your documents](https://pythonmates.com/learn/ai/rag-basics/): RAG (retrieval-augmented generation) lets an LLM answer from your own documents. You split documents into chunks, find the chunks most relevant to the question, and paste them into the prompt with an instruction to answer only from that context. The model then answers with your facts instead of guessing. - [Build an AI API with FastAPI](https://pythonmates.com/learn/ai/fastapi-for-ai/): FastAPI turns Python functions into web endpoints: decorate a function with @app.post("/ask"), describe the request body with a Pydantic model, and FastAPI validates input, converts JSON and writes interactive API docs for you. Because it's async, one server can wait on many LLM calls at once, and it can stream answers token by token. ## Optional - [How to learn Python with AI](https://pythonmates.com/guides/learn-python-with-ai/): prompts that teach instead of solve, checking AI code, a 6-week plan - [Python basics cheat sheet](https://pythonmates.com/cheat-sheets/python-basics/): Python basics on one page: variables, strings and f-strings, lists, dicts, sets, conditions, loops, functions, files and errors — modern Python 3 syntax. - [pandas cheat sheet](https://pythonmates.com/cheat-sheets/pandas/): pandas on one page: create and load DataFrames, inspect, select and filter, add columns, groupby and aggregate, sort, merge, handle missing values and save results. - [Python for AI cheat sheet](https://pythonmates.com/cheat-sheets/python-for-ai/): Python for AI on one page: NumPy arrays, matplotlib charts, scikit-learn train/test/predict, calling an LLM API, structured output with Pydantic, and a minimal RAG loop. - [Full course text](https://pythonmates.com/llms-full.txt): every lesson in one plain-text file - [Practice exercises](https://pythonmates.com/practice/): all exercises with automatic checking - [About](https://pythonmates.com/about/) - [AIMates](https://aimates.org/): sister site on using AI at work