Programming language · Beginner to advanced

Learn Python step by step

Start with your first Python program and progress to clean, tested applications, asynchronous programming and project packaging. Every module explains the idea in plain language, walks through a code example and gives you a small task to try yourself.

Version snapshot: Python 3.15.1. Latest stable release as of 22 October 2026. Python 3.15.1 is a maintenance update to the 3.15 feature release. Check library and hosting compatibility before choosing it for a production project.

Before you begin

No programming experience is required. Install Python 3.15.1 and an editor, or use an online Python shell to begin. If a library or hosting service does not yet support 3.15, use a supported version such as 3.14 for that project.

What you’ll be able to do

Build command-line tools, automate repetitive work, read and write data, and structure small applications with tests.

Work through the modules in order if you’re new to Python. If you already know the basics, use the contents list to jump to a topic. Try each example by changing one value, running it again and explaining the result in your own words.

Python terms in simple language

Interpreter
The program that reads Python instructions and runs them.
Variable
A name you use to store and find a value in your program.
Function
A named set of instructions you can reuse whenever you need the same job done.
Exception
A signal that something went wrong, such as trying to turn a word into a number.
Iterable
A value you can go through one item at a time, such as a list or a string.
Generator
A function that provides values one at a time instead of keeping every result in memory.
Decorator
A wrapper that adds a feature, such as timing or logging, around an existing function.
Context manager
A tool that safely starts and cleans up work, for example opening and closing a file.
Asynchronous code
Code that can wait for slow tasks, such as network requests, without stopping other work.
In this guide · 15 modules
  1. Key terms in simple language
  2. Set up Python and run your first program
  3. Variables, names and basic types
  4. Strings, formatting and input
  5. Operators, conditions and branching
  6. Loops and iteration
  7. Lists, tuples, dictionaries and sets
  8. Functions, parameters and scope
  9. Modules, packages and virtual environments
  10. Errors, exceptions and defensive code
  11. Files, paths and structured data
  12. Classes, objects and composition
  13. Comprehensions, iterators and generators
  14. Type hints, dataclasses and maintainable APIs
  15. Decorators, context managers and asynchronous I/O
  16. Testing, debugging and packaging a small app
  17. Final project
  18. Official references
MODULE 01 / 15 · CONCEPT EXPLAINED

Set up Python and run your first program

Python is a programming language, and the interpreter is the program that reads your code and runs it. Save the instructions in a file ending in .py, then run that file from a terminal with python filename.py. print shows a result so you can check what your program did. Text values are called strings and can be written inside single or double quotes.

Follow this example
print('Hello, world!')
print(2 + 3)
Try it yourself: Print your name and one goal for learning Python. Run the file again after changing the text.
MODULE 02 / 15 · CONCEPT EXPLAINED

Variables, names and basic types

A variable is a label your program uses to find a value again, much like a name on a storage box. Python recognizes common kinds of values: int means a whole number, float means a number with a decimal, str means text, and bool means True or False. Choose names such as lessons_finished so another person can understand your code. Avoid using names like list because Python already uses them for built-in tools.

Follow this example
learner_name = 'Asha'
lessons_finished = 3
progress = 0.25
is_enrolled = True
print(learner_name, lessons_finished)
Try it yourself: Create variables for a product name, price and stock count, then print a short summary.
MODULE 03 / 15 · CONCEPT EXPLAINED

Strings, formatting and input

A string is text, such as a name or a message. You can clean text with strip(), change its letter case with lower(), and replace one part with another. An f-string makes a sentence from text and values by placing each value inside braces. One detail to remember: input() always gives you text, even when someone types digits, so convert that answer to int or float before calculating with it.

Follow this example
name = input('Your name: ').strip()
age = int(input('Your age: '))
print(f'Hi {name}; next year you will be {age + 1}.')
Try it yourself: Ask for two numbers, convert them to integers, and print their sum and product.
MODULE 04 / 15 · CONCEPT EXPLAINED

Operators, conditions and branching

Operators are symbols that do work with values: + adds numbers, while == checks whether two values are equal. A comparison produces a yes-or-no result called a Boolean. if, elif and else let a program choose what to do, like a set of rules for deciding a delivery fee. Python uses indentation to show which instructions belong to each choice, so consistent spaces are part of the program’s meaning.

Follow this example
score = 78
if score >= 90:
    grade = 'A'
elif score >= 60:
    grade = 'Pass'
else:
    grade = 'Retry'
print(grade)
Try it yourself: Write a shipping-cost rule that gives free delivery above a chosen order total.
MODULE 05 / 15 · CONCEPT EXPLAINED

Loops and iteration

A loop repeats a small set of instructions. Use for to work through items one by one, such as every topic in a list. Use while when the program should keep going until something changes, such as asking again until the user enters a valid answer. break ends a loop early; continue skips the current item. enumerate is useful when you want both an item and its position, like numbering a list of lessons.

Follow this example
topics = ['types', 'loops', 'functions']
for number, topic in enumerate(topics, start=1):
    print(f'{number}. {topic}')
Try it yourself: Loop over 1 through 20 and print only the numbers divisible by three.
MODULE 06 / 15 · CONCEPT EXPLAINED

Lists, tuples, dictionaries and sets

Choose a collection based on how you use the data: lists are ordered and mutable, tuples are ordered and usually fixed, dictionaries map unique keys to values, and sets store unique members. Membership checks such as item in collection make intent clear.

Follow this example
course = {'name': 'Python', 'modules': 12}
modules = ['types', 'loops', 'functions']
completed = {'types'}
course['modules'] = len(modules)
print('loops' in modules, completed)
Try it yourself: Model a small library book using a dictionary and keep a list of three titles.
MODULE 07 / 15 · CONCEPT EXPLAINED

Functions, parameters and scope

Functions name a reusable unit of work. Pass data through parameters and return results instead of relying on hidden global state. Default values are evaluated once, so avoid mutable defaults such as [] and use None when a fresh list is needed.

Follow this example
def calculate_total(prices, tax_rate=0.0):
    subtotal = sum(prices)
    return subtotal * (1 + tax_rate)

print(calculate_total([100, 50], tax_rate=0.18))
Try it yourself: Write a function that accepts a list of scores and returns the average; decide what it should do for an empty list.
MODULE 08 / 15 · CONCEPT EXPLAINED

Modules, packages and virtual environments

A module is a Python file; a package groups modules. Import only what you need and keep application code separate from entry-point code. A virtual environment gives one project isolated dependencies. Record required packages so another developer can reproduce the environment.

Follow this example
python -m venv .venv
# Windows: .venv\Scripts\activate
# macOS/Linux: source .venv/bin/activate
python -m pip install requests
python -m pip freeze > requirements.txt
Try it yourself: Create a project folder with app.py and a helper module. Import one function from the helper and run it.
MODULE 09 / 15 · CONCEPT EXPLAINED

Errors, exceptions and defensive code

An exception signals that an operation could not complete. Catch only errors you can handle, keep the try block small and give the user a useful message. Use finally for cleanup that must run, and raise a clear exception when a function receives invalid input.

Follow this example
def read_count(text):
    try:
        return int(text)
    except ValueError as error:
        raise ValueError('Count must be a whole number.') from error

print(read_count('12'))
Try it yourself: Make a safe integer-input helper and show a helpful message instead of a traceback for invalid input.
MODULE 10 / 15 · CONCEPT EXPLAINED

Files, paths and structured data

Use pathlib for paths and open files with a with block so they close even if an error occurs. Choose an explicit text encoding. JSON is useful for simple structured data; validate external data because a valid JSON document may still have the wrong shape.

Follow this example
import json
from pathlib import Path

data = {'name': 'Asha', 'done': ['types']}
path = Path('progress.json')
path.write_text(json.dumps(data, indent=2), encoding='utf-8')
loaded = json.loads(path.read_text(encoding='utf-8'))
print(loaded['name'])
Try it yourself: Save a small task list as JSON, then load it and print only incomplete tasks.
MODULE 11 / 15 · CONCEPT EXPLAINED

Classes, objects and composition

A class defines how objects store state and provide behavior. __init__ sets up a new instance; self refers to that instance. Use composition when one object can work with another, and introduce inheritance only for a genuine “is a” relationship. Keep classes focused on one clear responsibility.

Follow this example
class Timer:
    def __init__(self, label):
        self.label = label
        self.seconds = 0

    def add(self, seconds):
        if seconds < 0:
            raise ValueError('seconds must be non-negative')
        self.seconds += seconds

timer = Timer('practice')
timer.add(25)
print(timer.label, timer.seconds)
Try it yourself: Create a Book class with title and author, then add a method that returns a readable label.
MODULE 12 / 15 · CONCEPT EXPLAINED

Comprehensions, iterators and generators

A comprehension builds a collection from an iterable in a compact, readable expression. An iterator yields one item at a time; a generator function uses yield to produce values lazily, which can save memory for large or streaming inputs. Prefer a regular loop if the comprehension becomes hard to understand.

Follow this example
squares = [number * number for number in range(1, 6)]

def read_nonblank(lines):
    for line in lines:
        cleaned = line.strip()
        if cleaned:
            yield cleaned

print(squares)
Try it yourself: Generate even numbers from a range, then write a generator that yields only non-empty lines.
MODULE 13 / 15 · CONCEPT EXPLAINED

Type hints, dataclasses and maintainable APIs

Type hints document expected inputs and outputs and help editors and static checkers find mistakes; Python does not enforce them at runtime by default. Dataclasses remove repetitive initialization code for simple data records. Add hints where they clarify a public function or a complex value.

Follow this example
from dataclasses import dataclass

@dataclass
class Lesson:
    title: str
    minutes: int

def total_minutes(lessons: list[Lesson]) -> int:
    return sum(lesson.minutes for lesson in lessons)
Try it yourself: Add type hints to your task-list functions and represent each task with a dataclass.
MODULE 14 / 15 · CONCEPT EXPLAINED

Decorators, context managers and asynchronous I/O

A decorator wraps a function to add cross-cutting behavior such as logging; functools.wraps preserves its metadata. A context manager sets up and reliably releases a resource. async and await coordinate I/O-bound work without blocking the event loop; they do not automatically make CPU-heavy code faster.

Follow this example
from contextlib import contextmanager

@contextmanager
def managed_message(label):
    print(f'Open {label}')
    try:
        yield
    finally:
        print(f'Close {label}')

with managed_message('report'):
    print('Working')
Try it yourself: Wrap a function with a simple timing or logging decorator, then compare sequential and asynchronous network calls.
MODULE 15 / 15 · CONCEPT EXPLAINED

Testing, debugging and packaging a small app

Tests turn expected behavior into repeatable checks. Start with small unit tests for edge cases, use assertions sparingly in application code, and run tests before sharing changes. Add a README with setup and run steps; keep secrets out of source control and pin production dependencies with a deliberate update process.

Follow this example
def is_even(value):
    return value % 2 == 0

def test_is_even():
    assert is_even(4) is True
    assert is_even(5) is False

if __name__ == '__main__':
    test_is_even()
    print('All checks passed')
Try it yourself: Build a command-line expense tracker with input validation, JSON storage, at least five tests and a README.
PUT THE MODULES TOGETHER

Your final project

Build a command-line study planner that saves tasks, validates user input, reports progress and has automated tests. Write down what the project should do, build it in small steps, and include a README that explains how to run it.

Find a guided course →

Official documentation and further reading

Use primary documentation for current language rules and version changes. The examples in this guide are learning starting points; verify details for the exact runtime and browser support your project needs.

Frequently asked questions

Can I learn Python with no coding background?

Yes. Begin with variables, conditions and loops, and run every example yourself before moving to the next module.

Do I need Python 3.15.1 for every project?

The guide examples are checked against Python 3.15.1. Existing production projects may use another supported version, so check the project, hosting platform and package compatibility before upgrading.