[ Web Proxy ]
URL:
Viewing: https://www.pythonbyexample.dev [Back]  [Original]

Python By Example Skip to main content Python By ExampleJourneysAbout

Python By Example

Learn Python with small, editable examples backed by the official Python 3.13 docs. Run each snippet in an isolated Dynamic Python Worker using the newest Python version currently supported by Cloudflare Workers/Pyodide.

Search examples

Basics

Hello World

The first Python program prints a line of text.

Values

Python programs evaluate expressions into objects such as text, numbers, booleans, and None.

Literals

Literals write values directly in Python source code.

Numbers

Python numbers include integers, floats, and complex values.

Booleans

Booleans represent truth values and combine with logical operators.

Operators

Operators combine, compare, and test values in expressions.

None

None represents expected absence, distinct from missing keys and errors.

Variables

Names are bound to values with assignment.

Constants

Python uses naming conventions and optional types for values that should not change.

Truthiness

Python conditions use truthiness, not only explicit booleans.

Object Lifecycle

Names keep objects reachable until the last reference goes away.

Data Model

Equality and Identity

== compares values, while is compares object identity.

Mutability

Some objects change in place, while others return new values.

Special Methods

Special methods connect your objects to Python syntax and built-ins.

Truth and Size

__bool__ and __len__ decide how objects behave in truth tests and len().

Container Protocols

Container methods connect objects to indexing, membership, and item assignment.

Callable Objects

__call__ lets an instance behave like a function while keeping state.

Operator Overloading

Operator methods let objects define arithmetic and comparison syntax.

Attribute Access

Attribute hooks customize lookup, missing attributes, and assignment.

Bound and Unbound Methods

instance.method binds self automatically; Class.method is a plain function.

Descriptors

Descriptors customize attribute access through __get__, __set__, or __delete__.

Context Managers

with ensures setup and cleanup happen together.

Delete Statements

del removes bindings, items, and attributes rather than producing a value.

Text

Strings

Strings are immutable Unicode text sequences.

Bytes and Bytearray

bytes and bytearray store binary data, not Unicode text.

String Formatting

f-strings turn values into readable text at the point of use.

Regular Expressions

The re module searches and extracts text using regular expressions.

Control Flow

Conditionals

if, elif, and else choose which block runs.

Guard Clauses

Guard clauses handle boundary cases early so the main path stays flat.

Assignment Expressions

The walrus operator assigns a value inside an expression.

For Loops

for iterates over values produced by an iterable.

Break and Continue

break exits a loop early, while continue skips to the next iteration.

Loop Else

A loop else block runs only when the loop did not end with break.

Match Statements

match selects cases using structural pattern matching.

Advanced Match Patterns

match patterns can destructure sequences, combine alternatives, and add guards.

While Loops

while repeats until changing state makes a condition false.

Iteration

Iterating over Iterables

for loops consume values from any iterable object.

Iterators

iter and next expose the protocol behind for loops.

Iterator vs Iterable

Iterables produce fresh iterators; iterators are one-pass.

Sentinel Iteration

iter(callable, sentinel) repeats calls until a marker value appears.

Generators

yield creates an iterator that produces values on demand.

Yield From

yield from delegates part of a generator to another iterable.

Generator Expressions

Generator expressions use comprehension-like syntax to stream values lazily.

Itertools

itertools composes lazy iterator streams.

Collections

Lists

Lists are ordered, mutable collections.

Tuples

Tuples group a fixed number of positional values.

Unpacking

Unpacking binds names from sequences and mappings concisely.

Dictionaries

Dictionaries map keys to values for records, lookup, and structured data.

Sets

Sets store unique values and make membership checks explicit.

Slices

Slices copy meaningful ranges from ordered sequences.

Comprehensions

Comprehensions build collections by mapping and filtering iterables.

Comprehension Patterns

Comprehensions can use multiple for clauses and filters when the shape stays clear.

Sorting

sorted returns a new ordered list and key functions choose the sort value.

Collections Module

collections provides specialized containers for common data shapes.

Copying Collections

Copies can duplicate the outer container while nested objects may still be shared.

Functions

Functions

Use def to name reusable behavior and return results.

Keyword-only Arguments

Use * to require selected function arguments to be named.

Positional-only Parameters

Use / to mark parameters that callers must pass by position.

Args and Kwargs

*args collects extra positional arguments and **kwargs collects named ones.

Multiple Return Values

Python returns multiple values by returning a tuple and unpacking it.

Closures

Inner functions can remember values from an enclosing scope.

Partial Functions

functools.partial pre-fills arguments to make a more specific callable.

Global and Nonlocal

global and nonlocal choose which outer binding assignment should update.

Recursion

Recursive functions solve nested problems by calling themselves on smaller pieces.

Lambdas

lambda creates small anonymous function expressions.

Decorators

Decorators wrap or register functions using @ syntax.

Classes

Classes

Classes bundle data and behavior into new object types.

Inheritance and Super

Inheritance reuses behavior, and super delegates to a parent implementation.

Classmethods and Staticmethods

Three method shapes: instance, class, and static each receives a different first argument.

Dataclasses

dataclass generates common class methods for data containers.

Properties

@property keeps attribute syntax while adding computation or validation.

Metaclasses

A metaclass customizes how classes themselves are created.

Structured Data Shapes

dataclass, NamedTuple, and TypedDict each model records with different trade-offs.

Abstract Base Classes

ABC and abstractmethod enforce that subclasses implement required methods.

Errors

Exceptions

Use try, except, else, and finally to separate success, recovery, and cleanup.

Assertions

assert documents internal assumptions and fails loudly when they are false.

Exception Chaining

raise from preserves the original cause when translating exceptions.

Exception Groups

except* handles matching exceptions inside an ExceptionGroup.

Warnings

warnings report soft problems without immediately stopping the program.

Custom Exceptions

Custom exception classes name failures that belong to your domain.

Modules

Modules

Modules organize code into namespaces and expose reusable definitions.

Import Aliases

as gives imported modules or names a local alias.

Packages

Packages organize modules into importable directories.

Virtual Environments

Virtual environments isolate a project's Python packages.

Types

Type Hints

Annotations document expected types and power static analysis.

Runtime Type Checks

type, isinstance, and issubclass inspect runtime relationships.

Union and Optional Types

The | operator describes values that may have more than one static type.

Type Aliases

Type aliases give a meaningful name to a repeated type shape.

TypedDict

TypedDict describes dictionaries with known string keys.

Literal and Final

Literal restricts exact values, while Final marks names that should not be rebound.

Callable Types

Callable annotations describe functions passed as values.

Generics and TypeVar

Generics preserve type information across reusable functions and classes.

ParamSpec

ParamSpec preserves callable parameter types through wrappers.

Overloads

overload describes APIs whose return type depends on argument types.

Casts and Any

Any and cast are escape hatches for places static analysis cannot prove.

NewType

NewType creates distinct static identities for runtime-compatible values.

Protocols

Protocol describes required behavior for structural typing.

Enums

Enum defines symbolic names for a fixed set of values.

Standard Library

Number Parsing

int() and float() parse text into numbers and raise ValueError on bad input.

JSON

json encodes Python values as JSON text and decodes them back.

Logging

logging records operational events without using print as infrastructure.

Testing

Tests make expected behavior executable and repeatable.

Subprocesses

subprocess runs external commands with explicit arguments and captured outputs.

Threads and Processes

Threads share memory, while processes run in separate interpreters.

Networking

Networking code exchanges bytes across explicit protocol boundaries.

Dates and Times

datetime represents dates, times, durations, formatting, and parsing.

CSV Data

csv reads and writes row-shaped text data.

Async

Async Await

async def creates coroutines, and await pauses until awaitable work completes.

Async Iteration and Context

async for and async with consume asynchronous streams and cleanup protocols.

adewale/pythonbyexample Python 3.13 docs Privacy
Web Proxy Viewer  |  New URL  |  Original Page