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.
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.
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.
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 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.
print('Hello, world!')
print(2 + 3)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.
learner_name = 'Asha'
lessons_finished = 3
progress = 0.25
is_enrolled = True
print(learner_name, lessons_finished)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.
name = input('Your name: ').strip()
age = int(input('Your age: '))
print(f'Hi {name}; next year you will be {age + 1}.')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.
score = 78
if score >= 90:
grade = 'A'
elif score >= 60:
grade = 'Pass'
else:
grade = 'Retry'
print(grade)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.
topics = ['types', 'loops', 'functions']
for number, topic in enumerate(topics, start=1):
print(f'{number}. {topic}')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.
course = {'name': 'Python', 'modules': 12}
modules = ['types', 'loops', 'functions']
completed = {'types'}
course['modules'] = len(modules)
print('loops' in modules, completed)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.
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))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.
python -m venv .venv
# Windows: .venv\Scripts\activate
# macOS/Linux: source .venv/bin/activate
python -m pip install requests
python -m pip freeze > requirements.txtAn 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.
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'))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.
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'])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.
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)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.
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)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.
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)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.
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')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.
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')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 →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.
Yes. Begin with variables, conditions and loops, and run every example yourself before moving to the next module.
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.