Skip to the workspace
Pebellslearn by building

Python syntax & reference

Find the form you need, compare how it behaves, and open the complete explanation when you need more depth.

Python 3.10+ syntax; individual entries identify newer features. Browser exercises use the configured Python runner.

41 matching syntax entries

Names and values

Learn in depth →

Assignment binds a name to an object. Rebinding a name does not change other names.

name = expression

Example

a = [1]
b = a
a = [2]
print(a, b)

Result

[2] [1]

Watch for: Two names may refer to the same mutable object; distinguish rebinding from mutation.

Practise this topic →

Types and conversion

Learn in depth →

A type describes the operations a value supports. Conversion constructs a value of another type.

type(value); int(text); float(text); str(value)

Example

print(type(3).__name__, int("42"), str(False))

Result

int 42 False

Watch for: int("3.5") raises ValueError. int(3.9) truncates toward zero, not toward the nearest integer.

Practise this topic →

Truth and fallback values

Learn in depth →

Conditions test truthiness; and/or return operands, while not returns a boolean.

value or fallback; a and b; not value

Example

print(bool([]), bool("0"))
print(0 or 10, "" or "guest")

Result

False True
10 guest

Watch for: A fallback using or replaces every falsy value, including zero. Use an explicit None check when zero is valid.

Practise this topic →

Division, remainder and powers

Learn in depth →

Numeric operators calculate values; floor division rounds the quotient down.

a / b; a // b; a % b; a ** b

Example

print(7 / 2, 7 // 2, -7 // 2, 7 % 2, 2 ** 3)

Result

3.5 3 -4 1 8

Watch for: Division by zero raises ZeroDivisionError. Binary floating point cannot represent every decimal exactly.

Practise this topic →

Equality, identity and membership

Learn in depth →

Equality compares values, identity compares objects, and membership asks whether an item is present.

a == b; a is b; item in container

Example

a = [1]
b = [1]
print(a == b, a is b, 1 in a)
print(1 < 2 < 3)

Result

True False True
True

Watch for: Use is None for the singleton None. Do not use is to compare numbers or strings.

Practise this topic →

Indexing a string

Learn in depth →

An index selects one Unicode code point from a string. Negative indices count from the end.

text[index]; text[-1]

Example

s = "CANTEEN"
print(s[0], s[-1], len(s))

Result

C N 7

Watch for: An invalid single index raises IndexError. A user-perceived character can contain multiple code points.

Practise this topic →

Slices and omitted bounds

Learn in depth →

A slice selects positions from start toward stop, excluding stop, at the chosen step.

Try different slice boundaries

Choose the boundaries. Follow the selected positions.

A slice visits positions toward its stop boundary. The stop position is excluded; reversing the step changes the direction.

0C-7
1A-6
2N-5
3T-4
4E-3
5E-2
6N-1

s[1:4]→"ANT"

Interactive model of Python slicing over Unicode code points. A visible character may contain several code points. Blank bounds are omitted, which differs from explicitly using -1 with a negative step.

text[start:stop:step]

Example

s = "CANTEEN"
print(s[1:4], s[-3:], s[::2], s[::-1])
print(repr(s[99:]))

Result

ANT EEN CNEN NEETNAC
''

Watch for: Out-of-range bounds are clipped. Step zero raises ValueError. stop-start is not a general slice-length formula.

Practise this topic →

Cleaning and splitting text

Learn in depth →

String methods return results; they do not modify the original string.

text.strip(); text.split(sep); separator.join(parts)

Example

raw = "  Asha,Rao  "
parts = raw.strip().split(",")
print(" ".join(parts))
print(repr(raw))

Result

Asha Rao
'  Asha,Rao  '

Watch for: strip(chars) removes any listed characters from both ends, not an exact prefix. Use removeprefix for a prefix.

Practise this topic →

Formatting values in text

Learn in depth →

An f-string evaluates expressions and formats the resulting values.

f"{expression:format_spec}"

Example

price = 12.5
print(f"Total: {price:.2f}")
print(f"{7:04d}")

Result

Total: 12.50
0007

Watch for: Formatting creates text. It does not change the numeric value or solve decimal arithmetic precision.

Practise this topic →

Branching and match

Learn in depth →

if/elif selects the first true branch; match checks a subject against patterns.

if condition: ...
elif condition: ...
else: ...

Example

score = 82
if score >= 80:
    print("distinction")
elif score >= 50:
    print("pass")
else:
    print("retry")

Result

distinction

Watch for: Order specific conditions before broader ones. A bare name in a match pattern captures a value rather than comparing an existing variable.

Practise this topic →

Iteration with enumerate and zip

Learn in depth →

A for loop requests successive values from an iterable. enumerate adds positions; zip combines streams.

for value in iterable: ...
enumerate(items, start=1); zip(left, right)

Example

for number, (name, score) in enumerate(zip(["Asha", "Om"], [8, 9]), start=1):
    print(number, name, score)

Result

1 Asha 8
2 Om 9

Watch for: zip stops at the shortest iterable by default. zip(..., strict=True) detects unequal lengths on Python 3.10+.

Practise this topic →

Ranges and loop else

Learn in depth →

range describes integer steps without storing a list. Loop else runs if no break occurred.

range(stop); range(start, stop, step)
for ...: ...
else: ...

Example

print(list(range(5, 0, -2)))
for n in [1, 3, 5]:
    if n % 2 == 0:
        break
else:
    print("no even value")

Result

[5, 3, 1]
no even value

Watch for: The stop is excluded. continue does not suppress loop else; break does.

Practise this topic →

Returning versus printing

Learn in depth →

return supplies a value to the caller. print sends text to an output stream.

def name(parameters):
    return expression

Example

def add_fee(subtotal):
    return subtotal + 20

bill = add_fee(100)
print(bill - 10)

Result

110

Watch for: Falling off the end returns None. A printed value cannot be used as the function result.

Practise this topic →

Argument forms

Learn in depth →

Parameters bind caller inputs; / and * restrict how arguments can be supplied.

def f(positional_only, /, normal, *, keyword_only): ...

Example

def quote(amount, /, tax=0, *, currency="INR"):
    return amount + tax, currency
print(quote(100, 18, currency="INR"))

Result

(118, 'INR')

Watch for: A default is evaluated when def executes. Use None and create a fresh container inside for a per-call mutable default.

Practise this topic →

Packing and unpacking

Learn in depth →

A tuple can carry several results. *args packs extra positional arguments and **kwargs packs keyword arguments.

a, b = pair
f(*values, **options)

Example

def summarize(*values, **options):
    return sum(values), options.get("unit", "items")
amount, unit = summarize(*[2, 3], unit="kg")
print(amount, unit)

Result

5 kg

Watch for: Unpacking must match the expected shape unless a starred target collects the remainder.

Practise this topic →

Handling expected failures

Learn in depth →

try/except handles selected exceptions; finally runs cleanup when control leaves the try statement.

try: ...
except ValueError as error: ...
else: ...
finally: ...

Example

try:
    number = int("bad")
except ValueError:
    print("invalid number")
finally:
    print("finished")

Result

invalid number
finished

Watch for: Catch the narrow failures you can handle. Returning from finally can hide a pending exception.

Practise this topic →

Lists, copying and mutation

Learn in depth →

A list is an ordered mutable collection. A shallow copy creates a new outer container.

items.append(value); items.extend(values); items.copy()

Example

a = [[1]]
b = a.copy()
b[0].append(2)
print(a, b)
print(a.append([3]))

Result

[[1, 2]] [[1, 2]]
None

Watch for: append and sort mutate in place and return None. Shallow copies still share nested objects.

Practise this topic →

Comprehensions

Learn in depth →

A comprehension constructs a collection from an iterable with optional filtering.

[expression for item in iterable if condition]

Example

squares = [n * n for n in range(6) if n % 2 == 0]
print(squares)
print({n: n * n for n in range(3)})

Result

[0, 4, 16]
{0: 0, 1: 1, 2: 4}

Watch for: The if after the loop filters items. A conditional expression before the loop chooses a value for every item.

Practise this topic →

Dictionary lookup and iteration

Learn in depth →

A dictionary maps hashable keys to values and preserves insertion order.

mapping[key]; mapping.get(key, default); mapping.items()

Example

counts = {"tea": 2}
print(counts.get("coffee", 0))
for name, count in counts.items():
    print(name, count)

Result

0
tea 2

Watch for: [] raises KeyError for a missing key. get does not insert its default. setdefault may insert it.

Practise this topic →

Set operations

Learn in depth →

A set holds distinct hashable values and supports membership and set algebra.

a | b; a & b; a - b; a ^ b

Example

a, b = {1, 2}, {2, 3}
print(sorted(a | b), sorted(a & b), sorted(a - b))

Result

[1, 2, 3] [2] [1]

Watch for: {} is an empty dictionary; set() is an empty set. Do not rely on set iteration order.

Practise this topic →

Classes and instance state

Learn in depth →

A class defines behavior; instances hold their own state through attributes.

class Name:
    def __init__(self, value): ...

Example

class Counter:
    def __init__(self):
        self.value = 0
    def increment(self):
        self.value += 1
c = Counter()
c.increment()
print(c.value)

Result

1

Watch for: A mutable class attribute is shared across instances unless shadowed. Initialize per-instance lists in __init__.

Practise this topic →

Hashability and dictionary keys

Learn in depth →

A hashable object has a stable hash and equality behavior suitable for dictionary/set membership.

hash(value); {(key_part_1, key_part_2): value}

Example

location = (12, 18)
print({location: "sensor"}[location])

Result

sensor

Watch for: A tuple is hashable only if all its elements are hashable. Being immutable alone does not prove an arbitrary object is hashable.

Practise this topic →

Iterable versus iterator

Learn in depth →

An iterable supplies an iterator. An iterator retains a position and produces values through next.

iterator = iter(iterable)
next(iterator, default)

Example

source = [10, 20]
a, b = iter(source), iter(source)
print(next(a), next(a), next(b))
print(next(a, "end"))

Result

10 20 10
end

Watch for: A consumed iterator is not automatically reset. Creating an iterator from a list can start an independent traversal.

Practise this topic →

Generator functions

Learn in depth →

A function containing yield creates a generator whose execution suspends between yielded values.

def values():
    yield expression

Example

def values():
    print("started")
    yield 10
g = values()
print("created")
print(next(g))

Result

created
started
10

Watch for: Calling the generator function does not execute its body immediately. Exhaustion ends that generator instance.

Practise this topic →

Lazy expressions and islice

Learn in depth →

A generator expression computes values as requested; islice limits consumption.

(expression for item in iterable)
itertools.islice(iterator, count)

Example

from itertools import islice
g = (n * n for n in range(100))
print(list(islice(g, 3)))
print(next(g))

Result

[0, 1, 4]
9

Watch for: Laziness does not make retained source data disappear. Some operations buffer or consume the entire input.

Practise this topic →

Name lookup and closures

Learn in depth →

Functions resolve names through local, enclosing, global and built-in scopes. Closures retain bindings.

nonlocal name; global name

Example

def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment
c = make_counter()
print(c(), c())

Result

1 2

Watch for: Assignment makes a name local unless declared otherwise. Late-bound closures observe a binding at call time.

Practise this topic →

Decorators and wraps

Learn in depth →

A decorator transforms a function when its definition executes. wraps preserves useful metadata.

@decorator
def function(...): ...

Example

from functools import wraps
def traced(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper
@traced
def total(a, b):
    return a + b
print(total(2, 3), total.__name__)

Result

5 total

Watch for: Stacked decorators apply from the bottom upward. A synchronous wrapper does not automatically await an async function.

Practise this topic →

Counting and grouping

Learn in depth →

Counter counts hashable values; defaultdict creates a missing value when accessed with [].

Counter(iterable); defaultdict(factory)

Example

from collections import Counter, defaultdict
print(sorted(Counter("banana").items()))
groups = defaultdict(list)
groups["fruit"].append("pear")
print(dict(groups))

Result

[('a', 3), ('b', 1), ('n', 2)]
{'fruit': ['pear']}

Watch for: defaultdict.get does not invoke the factory. Counter entries may have zero or negative counts.

Practise this topic →

Queues and priority queues

Learn in depth →

deque supports both ends; heapq keeps the smallest item at the root of a list-based min-heap.

deque.append; deque.popleft; heappush; heappop

Example

from collections import deque
from heapq import heappush, heappop
q = deque([1, 2]); q.append(3)
heap = []; heappush(heap, 8); heappush(heap, 2)
print(q.popleft(), heappop(heap))

Result

1 2

Watch for: A heap is not a globally sorted list. Repeated heappop operations retrieve items in priority order.

Practise this topic →

Paths and resource ownership

Learn in depth →

Path represents filesystem paths; a with statement gives a resource a defined cleanup boundary.

Path("data") / "input.csv"
with path.open(encoding="utf-8") as handle: ...

Example

from pathlib import Path
p = Path("data") / "input.csv"
print(p.name, p.suffix)

Result

input.csv .csv

Watch for: Filesystem operations require appropriate permissions. Browser files live in a virtual filesystem unless explicitly exported.

Practise this topic →

Text versus bytes

Learn in depth →

str contains Unicode text; bytes contains integer byte values. Encoding and decoding cross that boundary.

text.encode("utf-8"); data.decode("utf-8")

Example

text = "café"
data = text.encode("utf-8")
print(len(text), len(data), data.decode("utf-8"))

Result

4 5 café

Watch for: The encoding must match the data. Ignoring decoding errors can silently lose information.

Practise this topic →

JSON serialization

Learn in depth →

JSON represents a restricted set of data types; dumps produces text and loads parses it.

json.dumps(value); json.loads(text)

Example

import json
text = json.dumps({"ok": True, "items": [1, 2]}, sort_keys=True)
print(text)
print(json.loads(text)["ok"])

Result

{"items": [1, 2], "ok": true}
True

Watch for: JSON object keys are strings. Python-specific types need an explicit representation; parsing is not schema validation.

Practise this topic →

CSV rows and newline handling

Learn in depth →

The csv module handles quoting and delimiters so a comma inside a field remains data.

csv.DictReader(handle); csv.DictWriter(handle, fieldnames=...)

Example

import csv, io
rows = csv.DictReader(io.StringIO('name,note\nAsha,"tea, please"\n'))
print(next(rows)["note"])

Result

tea, please

Watch for: For real files use open(..., newline="", encoding="utf-8"). A split(",") is not a CSV parser.

Practise this topic →

Regex matching and extraction

Learn in depth →

Regular expressions recognize text patterns; fullmatch checks the entire input.

re.search(pattern, text); re.fullmatch(pattern, text)

Example

import re
print(bool(re.fullmatch(r"[A-Z]{2}[0-9]{3}", "AB123")))
print(re.findall(r"[0-9]+", "a12 b7"))

Result

True
['12', '7']

Watch for: search can match a substring. Avoid ambiguous nested repetition with untrusted inputs; a match is not domain validation.

Practise this topic →

Imports and the entry point

Learn in depth →

Import locates and initializes a module, normally caching it in sys.modules. __name__ identifies its execution context.

import package.module
if __name__ == "__main__": ...

Example

import math
print(math.isqrt(17))

Result

4

Watch for: A local file named like a standard module can shadow it. An import may execute module-level code.

Practise this topic →

Environment and dependency commands

Learn in depth →

A virtual environment isolates an interpreter environment and its installed packages.

python -m venv .venv
python -m pip install package
python -m pip --version

Example

import sys
print(isinstance(sys.executable, str))

Result

True

Watch for: Activate using the command for your shell, or invoke the environment interpreter explicitly. Confirm which interpreter pip installs into.

Practise this topic →

Raising with context

Learn in depth →

raise from connects an application error to the lower-level failure that caused it.

raise DomainError("message") from error

Example

try:
    try:
        int("bad")
    except ValueError as error:
        raise RuntimeError("invalid record") from error
except RuntimeError as error:
    print(type(error.__cause__).__name__)

Result

ValueError

Watch for: Do not swallow failures or expose secrets in messages. Preserve enough context for diagnosis.

Practise this topic →

Test assertions and boundaries

Learn in depth →

A test compares observed behavior against a stated contract on chosen examples.

def test_behavior():
    assert actual == expected

Example

def divide(total, count):
    return total / count
assert divide(10, 2) == 5
print("contract example passed")

Result

contract example passed

Watch for: Use pytest locally for its discovery, parametrization and fixtures. Passing samples does not prove correctness for every input.

Practise this topic →

Annotations and optional values

Learn in depth →

Annotations describe expected types for tools and readers; Python does not enforce them automatically.

def parse(text: str) -> int | None: ...

Example

def parse(text: str) -> int | None:
    try:
        return int(text)
    except ValueError:
        return None
print(parse("7"), parse("bad"))

Result

7 None

Watch for: Run a configured type checker separately. A cast informs the checker; it does not validate a value at runtime. Union | syntax needs Python 3.10+.

Practise this topic →

Context managers and cleanup

Learn in depth →

A context manager defines entry and exit behavior around a with block.

with resource() as value: ...

Example

from contextlib import contextmanager
@contextmanager
def owned():
    print("enter")
    try:
        yield "resource"
    finally:
        print("exit")
with owned() as value:
    print(value)

Result

enter
resource
exit

Watch for: Exit logic must define what happens on failures. Returning True from __exit__ suppresses the exception.

Practise this topic →

Awaiting and scheduling

Learn in depth →

An async function call creates a coroutine. Awaiting or scheduling it arranges execution.

await operation()
asyncio.create_task(operation())
async with asyncio.TaskGroup() as group: ...

Example

import inspect
async def fetch():
    return 42
coroutine = fetch()
print(inspect.iscoroutine(coroutine))
coroutine.close()

Result

True

Watch for: Blocking calls still block an event-loop thread. Use cleanup in finally and normally re-raise cancellation after cleanup. TaskGroup needs Python 3.11+.

Practise this topic →
Complete explanation index (91 lessons indexed)

Basic Syntax & Output

Variables & Data Types

Operators & Math

Working with Strings

Conditionals

Loops

Type Casting & Input

Functions

Exceptions & Errors

Built-in Functions

Lists, Tuples & Sets

Dictionaries

Type Annotations

Capstone — Bill Splitter & Tip Calculator

Project 1 — Terminal Café POS

Project 2 — CSV Data Analyzer

Project 3 — Expense & Budget Tracker

Project 4 — Text Adventure

What Is OOP?

Classes & Instances

Encapsulation

Inheritance

Polymorphism

Abstraction

Dunder Methods

Names, Objects & Identity

Mutable, Immutable & Hashable

What Keeps an Object Alive

Capstone — The Inspector

Writing an Iterable by Hand

Generators: Functions That Pause

Chaining Generators into a Pipeline

Capstone — The Feed

Variable Scope & the LEGB Rule

Lambdas, map, filter & reduce

List & Set Comprehensions

Generator Expressions

Programming Paradigms

Closures & the Cell

Decorators

Decorators That Take Arguments

functools

Callables, *args & Signatures

Capstone — The Middleware Ring

Collections: Counter, defaultdict, namedtuple, OrderedDict

deque and heapq

Enum

math and random

itertools

Arrays & Linked Lists

HashMaps

Stacks, Queues & Heaps

Binary Search Trees

Recursion

Sorting Algorithms

pathlib

Reading & Writing, Text and Binary

Writing Your Own Context Manager

Unicode, str and bytes

Bytes, Buffers & struct

Capstone — The Yard

CSV & the Dialects Nobody Agrees On

JSON, and the Types It Cannot Hold

Pickle, and Why You Must Not Load Untrusted Data

sqlite3 & the DB-API

Capstone — The Vault

Regular Expressions

Groups, Named Captures & Lookaround

sub, split, finditer & Flags

Catastrophic Backtracking & When Not to Use Regex

Capstone — The Extractor

Modules, Packages & What import Really Does

Virtual Environments & Pinned Dependencies

pyproject.toml, Wheels & the Console Entry Point

The Hierarchy, `raise from` & `finally`

Logging

Capstone — The Black Box

Your First pytest Suite

Fixtures, Parametrisation & Scope

Doubles, patch & Test Seams

Properties, Coverage & Honest Green

pdb, Post-Mortem & Bisecting

unittest, doctest & tox

Capstone — The Test Rig

Package Managers

The Static Typing Ecosystem

Choosing a Web Framework

Threads and the GIL

Multiprocessing and Asyncio

Formatters, Linters and Docs

Capstone — Quarry, End to End

Technical sources and review date

Original Pebells examples. Reviewed 2026-10-28.

Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.