code-playpad

Python

Real CPython 3.14 via Pyodide, in the reader's browser. Move to another page through the nav links and the document is never torn down, so the worker and a warm Pyodide come with you: watch document alive in the strip above keep counting. Each move costs one fetch and a <main> swap, not the ~1–3s of starting Python again.

Jump to: Overview · Loops · Conditions · Modules

Overview: two editors, one Python

Both playgrounds below import the same runtime module, so they share a single Web Worker and a single Pyodide instance. Run them back to back: the second one does not reboot anything. Run them at the same time and the second waits — Python is single-threaded, so runs are queued.

import sys print("widget A ·", sys.version.split()[0]) total = sum(range(1, 101)) total import time print("widget B — sleeping 2s, keeping the queue busy") time.sleep(2) print("widget B done")
Proof of the shared worker: press Run on B, then immediately on A. A shows Running… but only starts once B finishes. If each widget had its own Pyodide, both would boot ~11 MB separately.

Stopping runaway code

There is no cooperative interrupt without SharedArrayBuffer (which needs site-wide COOP/COEP headers), so Stop terminates the worker and boots a fresh one. Queued runs survive and land on the new worker.

while True: pass

Reading input

input() really blocks: the prompt appears, a caret waits in the output, and the program continues when you answer. What you type is echoed the way a terminal echoes it, so the transcript reads back properly. Enter sends a line, EOF ends input.

The standard-input box is optional now — lines in it are used up first, before you are asked. Handy for scripted exercises; leave it empty to answer live.

name = input("name? ") age = int(input("age? ")) print(f"hello {name}, next year you turn {age + 1}")

Prompting in a loop works the same way — press EOF or send a blank line to stop.

total = 0 while True: line = input("number (blank to finish)? ") if not line: break total += int(line) print("sum:", total)

Packages load themselves

loadPackagesFromImports() runs before your code, so an import is all it takes.

import numpy as np grid = np.arange(9).reshape(3, 3) print(grid) grid.sum()

Light and dark

Press the moon or sun in the header to change this page. Widgets follow it until you choose for them, with the moon or sun on any widget or an editor theme such as Monokai from the palette. That choice is saved, every widget on the site follows it, and the page stays as it is. An explicit theme overrides both: the pair below stays put whichever way you toggle. All the theme settings are on the Options page.

print("pinned light") print("pinned dark")

Sizing

height="auto" fits the snippet — no dead space under a one-liner, no hidden lines under a long one, at any viewport width.

print("auto: exactly as tall as it needs to be")

max-height caps a long listing and scrolls inside it.

WEEKDAYS = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] MONTHS = [ "January", "February", "March", "April", "May", "June", ] print(len(WEEKDAYS), "days and", len(MONTHS), "months")

min-height gives a short exercise room to type in — the whole box is the editor, not just the first line.

# Your code here

Lazy loading

↓ scroll — the widget below boots only as it nears the viewport ↓
print("I did not exist in the network tab until you scrolled here.")

Loops

A lesson with its progress saved. Run a snippet and it counts as completed.

for

for i in range(5): print(i, "squared is", i * i)

while

n = 27 steps = 0 while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps += 1 print("collatz steps:", steps)
Edits are saved to IndexedDB under the persist id, so they survive navigation and a full reload.

Conditions

if / elif / else

score = 78 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print(grade)

Read-only example

Reference snippets can be runnable without being editable.

print("truthy" if [0] else "falsy") print("truthy" if [] else "falsy")
Lessons completed:

Modules: several files and packages

A widget can hold more than one file. They are written into Pyodide's filesystem before the run, next to the entry point and on sys.path, so ordinary import works — flat modules, packages with __init__.py, and plain data files you open(). Pick a file with the tabs; ▸ marks the one Run executes.

A package, a module, and an entry point

from geometry import Circle, Rectangle from report import table shapes = [Circle(1), Rectangle(2, 3), Circle(0.5)] print(table(shapes)) print() print("__name__ here is", __name__) sum(s.area() for s in shapes) """A real package: geometry/__init__.py re-exports the shape classes.""" from .shapes import Circle, Rectangle __all__ = ["Circle", "Rectangle"] from dataclasses import dataclass from math import pi @dataclass class Circle: radius: float def area(self) -> float: return pi * self.radius ** 2 @dataclass class Rectangle: width: float height: float def area(self) -> float: return self.width * self.height def table(shapes): rows = [f"{type(s).__name__:<10} {s.area():8.3f}" for s in shapes] total = sum(s.area() for s in shapes) rows.append(f"{'total':<10} {total:8.3f}") return "\n".join(rows)
Edit geometry/shapes.py — say, make Rectangle.area return 0 — and press Run. The module cache is cleared between runs, so the edit takes effect immediately instead of Python serving the copy it imported last time.

Tracebacks name the real file

The entry point is executed under its own path, so a failure inside a package points at geometry/shapes.py and its line number — not at <exec>.

from geometry.shapes import Circle print("about to fail") Circle(-1).area() from math import pi class Circle: def __init__(self, radius): self.radius = radius def area(self): if self.radius < 0: raise ValueError(f"radius must be positive, got {self.radius}") return pi * self.radius ** 2

Not just Python files

Anything in the file list lands on disk, so open(), the csv module, and relative paths behave normally. The working directory is the widget's own folder.

import csv from pathlib import Path rows = list(csv.DictReader(Path("stock.csv").open())) for row in rows: print(f"{row['item']:<8} {int(row['qty']):>4}") print("---") print("total", sum(int(r["qty"]) for r in rows)) item,qty bolts,120 nuts,340 washers,75
Files are per-widget but the runtime is still shared: these three playgrounds and every other one on this page use the same Worker, and each run rewrites its own file set first.