Natter SpritesGitHub

Command reference

What Natter can do

Everything a program can use in Natter: the language, the built-in functions, the standard modules, turtle, Kara, Pygame Zero, forms with guizero, numpy, plots, requests and files. Each module comes with a short example that runs as shown.

Natter aims to be plain Python: what is listed here behaves as in CPython 3.12 (and as the real libraries). Where it differs or something is missing, it says so. Press / to search.

01 · Basics

The language

Natter compiles Python 3 to bytecode and runs it in time slices. The table shows what works, with an example, and what does not, with the message Natter then shows. Every row ran while this page was built.

AreaWhat worksWhat does not
BasicsIntegers of any size, floats, strings, True/False, None; if/elif/else, while, for (also with else), break, continue, pass, multiple assignment a, b = b, a, chained comparisons 1 < x < 5, x if c else y.
for i in range(3):
    if i == 1:
        continue
    print(i, 2 ** 70)
match/case and the walrus operator := are missing.
x = 3
match x:
    case 3:
        print("drei")

SyntaxError: “x” does not belong here.

if (n := 5) > 3:
    print(n)

SyntaxError: “)” is missing here (found: :=).

NumbersArithmetic as in CPython: // and % with Python's signs, round() rounds halves to even, integers become big integers above 2^53, floats print the same digits as CPython.
print(round(2.5), -7 // 2, -7 % 3, 2 ** 100, 0.1 + 0.2)
Complex numbers are missing.
print(1 + 2j)

SyntaxError: Complex numbers (1j) do not exist in Natter.

Stringsf-strings with format specs, % formatting, str.format, slices, in, all the usual string methods (see methods).
n = "Ada"
print(f"{n:>5}|{3.14159:.2f}|{1234567:,}", "%d%%" % 5, "{} {}".format(1, 2))
No bytes: b"…", str.encode() and binary files are missing; the function format() is missing (the method str.format and f-strings work).
print(b"abc")

SyntaxError: Bytes (b"…") do not exist in Natter – use a normal text.

print(format(255, "x"))

NameError: “format” has no value yet.

Lists, tuples, dicts, setsIndexing and slicing (also negative and with a step), list, dict and set comprehensions, unpacking with *rest, set/frozenset with all set operations, del.
a, *rest = [3, 1, 2]
print(a, rest, [x * x for x in rest], {x % 2 for x in rest}, {k: len(k) for k in ["ab", "c"]})
dict | dict is missing (use update).
print({"a": 1} | {"b": 2})

TypeError: “dict” | “dict” is not possible.

Functionsdef with defaults, *args, **kwargs, keyword-only parameters after *, lambda, closures, global, nonlocal, decorators, recursion up to depth 1000 like CPython.
def gruss(name, *, laut=False, **extra):
    t = "Hallo " + name
    return t.upper() if laut else t
print(gruss("Ada", laut=True), (lambda x: x * 2)(21))
Positional-only parameters (/) are missing.
def f(a, /, b):
    return a + b

SyntaxError: A name is missing here (found: /).

Classesclass with inheritance (also multiple, MRO as in CPython), super(), @property with setter, @classmethod, @staticmethod, operators via __add__, __eq__, __lt__, __getitem__, __len__, __iter__, __call__, __getattr__ …
class Tier:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return "Tier " + self.name
class Hund(Tier):
    def __init__(self, name):
        super().__init__(name)
print(Hund("Bello"))
No subclasses of built-in types (class L(list)), no metaclasses; __setattr__ and __slots__ have no effect.
class L(list):
    pass

SyntaxError: You cannot (yet) derive a class from built-in types like list or dict.

class M(type):
    pass
class A(metaclass=M):
    pass

SyntaxError: Metaclasses and keywords in a class definition are not supported.

Exceptionstry/except/else/finally, raise, raise … from …, custom exception classes, all common built-in exceptions. Errors come with the line, the call stack and a hint in English or German.
class ZuKlein(Exception):
    pass
try:
    raise ZuKlein("unter 0")
except ZuKlein as e:
    print("Fehler:", e)
finally:
    print("fertig")
Exception groups (except*) are missing.
try:
    pass
except* ValueError:
    pass

SyntaxError: except* is not supported.

Generators, withyield, yield from, generator expressions (lazy), with with your own context managers (__enter__/__exit__).
def zaehle(n):
    yield from range(n)
print(sum(x * x for x in zaehle(4)))
async/await and threads are missing.
async def f():
    pass

SyntaxError: async/await does not exist in Natter.

Input and outputinput() pauses the program until the answer arrives; print with sep, end, file=sys.stderr.
name = input("Wie heißt du? ")
print("Hallo", name, sep=", ", end="!\n")
Modulesimport of standard modules and of the project's own files (helpers.py, packages with __init__.py, from . import x), import a.b, import x as y, from x import *.
import math as m
from os import path
print(m.floor(2.7), path.join("a", "b"))
Modules that do not exist (see the list on the left) raise ModuleNotFoundError.
import tkinter

ModuleNotFoundError: There is no module “tkinter”. Available are math and random.

Type hintsParsed and ignored, so programs from books run.
def doppelt(x: int) -> int:
    return 2 * x
zahlen: list = [1, 2]
print(doppelt(4), zahlen)
The module typing is missing (hints like List[int] do not need it if you write list).
from typing import List

ModuleNotFoundError: There is no module “typing”. Available are math and random.

Not availableLeft out on purpose: rarely needed in class, or it would make the page unsafe.eval, exec, dir, globals; ... equals None.
print(eval("1 + 2"))

NameError: “eval” has no value yet.

print(dir())

NameError: “dir” has no value yet.

02 · Basics

Built-in functions

Every program knows these names without an import. Parameters are shown as Natter checks them; x=… means it may be left out.

Example
zahlen = [5, 3, 8, 1]
print(len(zahlen), sum(zahlen), min(zahlen), max(zahlen))
print(sorted(zahlen, reverse=True))
for i, z in enumerate(zahlen, start=1):
    print(i, z, end="; ")
print()
print(list(zip("abc", range(3))), round(3.14159, 2), abs(-4), divmod(17, 5))
Output
4 17 1 8
[8, 5, 3, 1]
1 5; 2 3; 3 8; 4 1; 
[('a', 0), ('b', 1), ('c', 2)] 3.14 4 (3, 2)

Limits and differences from CPython

  • print(..., file=sys.stderr) writes to the error output (the console shows it in red).
  • hash() and id() return fixed numbers that differ from CPython; pow has no third (modulo) parameter.
  • type() with three arguments (creating classes) and zip(strict=True) are missing.

Funktionen

abs(x)

Absolute value.

all(iterable)

Are all items true?

any(iterable)

Is at least one item true?

bin(x)

Binary string, e.g. 0b101.

bool(x=…)

Truth value: 0, "", empty collections and None are False.

chr(i)

Character for a Unicode number.

dict(**kwargs) / dict(iterable)

New dictionary.

divmod(a, b)

Integer quotient and remainder as a tuple.

enumerate(iterable, start=…)

Pairs (number, item).

filter(function, iterable)

Keeps the items for which the function is true (None: the true items).

float(x=…)

Float from a string or number (also "inf", "nan").

getattr(object, name, default=…)

Reads an attribute by its name (with default if it is missing).

hasattr(object, name)

Does the attribute exist?

hex(x)

Hexadecimal string, e.g. 0xff.

input(prompt=…)

Asks for a line. The program waits until the answer is entered; the result is always a string.

int(x=…, base=…)

Integer from a string or float (truncates); with base from a string in that base.

isinstance(obj, class)

Is the value of the type (or one of the types in the tuple)?

iter(obj)

Iterator over a collection.

len(obj)

Number of items of a string, list, dict …

list(iterable=…)

New list, e.g. from a string, range or generator.

map(function, *iterables)

Applies a function to every item.

max(iterable, key=None, default=…) / max(a, b, …)

Largest value.

min(iterable, key=None, default=…) / min(a, b, …)

Smallest value.

next(iterator, default=…)

Next item of an iterator (or default).

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Opens a text file of the project, see files.

ord(c)

Unicode number of a character.

pow(base, exp)

Power base ** exp.

print(*objects, sep=" ", end="\n", file=None, flush=False)

Prints values, separated by sep, followed by end.

range(stop) / range(start, stop, step=1)

Sequence of numbers for for loops, excluding stop.

reversed(seq)

Iterator going backwards.

round(number, ndigits=…)

Rounds to ndigits places; exact halves go to the even number (round(2.5) == 2) as in CPython.

set(iterable=…)

New set (duplicates disappear).

setattr(object, name, value)

Sets an attribute by its name.

slice(stop) / slice(start, stop, step=None)

Slice object for a[s].

sorted(iterable, key=…, reverse=…)

New sorted list (stable), optionally with key and reverse.

str(object=…)

String of a value (as print shows it).

sum(iterable, start=…)

Sum; floats exactly as in CPython (sum([0.1] * 10) == 1.0).

super(type, object)

Access to the methods of the base class (usually without arguments: super().__init__()).

tuple(iterable=…)

New tuple.

type(object)

Type of a value, e.g. <class 'int'>.

vars(object)

Attributes of an object as a dict.

zip(*iterables)

Combines several sequences pairwise (stops at the shortest).

  • callable(obj)
  • classmethod(function)
  • delattr(object, name)
  • frozenset(iterable=…)
  • hash(obj)
  • id(obj)
  • issubclass(class, classinfo)
  • oct(x)
  • property(fget=…, fset=…, fdel=…)
  • repr(obj)
  • staticmethod(function)

Exceptions

BaseException SystemExit KeyboardInterrupt GeneratorExit Exception ArithmeticError FloatingPointError OverflowError ZeroDivisionError AssertionError AttributeError EOFError ImportError ModuleNotFoundError LookupError IndexError KeyError NameError UnboundLocalError OSError FileNotFoundError PermissionError FileExistsError IsADirectoryError NotADirectoryError TimeoutError ConnectionError RuntimeError NotImplementedError RecursionError StopIteration SyntaxError IndentationError TabError TypeError ValueError IOError EnvironmentError

Missing compared with CPython

aiter anext ascii breakpoint bytearray bytes compile complex dir eval exec format globals help locals memoryview __import__

03 · Basics

Methods of the built-in types

Methods of strings, lists, tuples, dicts and sets. They all behave as in CPython. int and float have no methods (e.g. bit_length and is_integer are missing).

Example
satz = "  Natter ist eine kleine Schlange  "
woerter = satz.strip().split()
print(woerter, "-".join(woerter).upper())
print(satz.count("e"), satz.find("klein"), satz.replace("klein", "groß").strip())
zahlen = [3, 1, 2]
zahlen.append(5)
zahlen.sort()
print(zahlen, zahlen.index(5), zahlen.pop())
alter = {"Ada": 36}
alter.setdefault("Linus", 21)
for name, jahre in alter.items():
    print(name, alter.get(name), jahre)
Output
['Natter', 'ist', 'eine', 'kleine', 'Schlange'] NATTER-IST-EINE-KLEINE-SCHLANGE
6 18 Natter ist eine große Schlange
[1, 2, 3] 3 5
Ada 36 36
Linus 21 21

Limits and differences from CPython

  • Methods not listed below are missing, e.g. str.encode, str.partition, str.maketrans/translate, str.removeprefix/removesuffix, dict.fromkeys, dict.popitem; list.sort takes only key and reverse.

str

count(sub, start=…, end=…)

How often does sub occur?

find(…)

Position of sub or -1.

format(…)

Fills values into {}.

isdigit(…)

Only digits?

join(iterable)

Joins the strings of a list with this string in between.

lower(…)

Lower case.

replace(old, new, count=…)

Replaces old with new.

split(sep=…, maxsplit=…)

Splits at sep (without: at whitespace).

startswith(prefix)

Does the string start with prefix (also a tuple)?

strip(chars=…)

Removes whitespace (or chars) at both ends.

upper(…)

Upper case.

  • capitalize(…)
  • center(width, fillchar=…)
  • endswith(suffix)
  • expandtabs(tabsize=…)
  • index(…)
  • isalnum(…)
  • isalpha(…)
  • islower(…)
  • isnumeric(…)
  • isspace(…)
  • isupper(…)
  • ljust(width, fillchar=…)
  • lstrip(chars=…)
  • rfind(…)
  • rindex(…)
  • rjust(width, fillchar=…)
  • rstrip(chars=…)
  • splitlines(keepends=…)
  • swapcase(…)
  • title(…)
  • zfill(width)

list

append(object)

Adds an item at the end.

index(value)

Position of the first occurrence.

insert(index, object)

Inserts at position index.

pop(index=…)

Removes the last item (or the one at index) and returns it.

remove(value)

Removes the first item with this value.

sort(…)

Sorts the list in place (stable), key=, reverse=.

  • clear(…)
  • copy(…)
  • count(value)
  • extend(iterable)
  • reverse(…)

tuple

  • count(value)
  • index(value)

dict

get(key, default=…)

Value for key or default.

items(…)

Pairs (key, value).

keys(…)

The keys.

pop(key, default=…)

Removes key and returns its value.

setdefault(key, default=…)

Value for key; if it is missing, default is stored.

update(…)

Takes over the entries of another dict.

values(…)

The values.

  • clear(…)
  • copy(…)

set

add(elem)

Adds an item.

difference(…)

Difference (also a - b).

discard(elem)

Removes an item if present.

intersection(…)

Intersection (also a & b).

union(…)

Union (also a | b).

  • clear(…)
  • copy(…)
  • difference_update(…)
  • intersection_update(…)
  • isdisjoint(other)
  • issubset(other)
  • issuperset(other)
  • pop(…)
  • remove(elem)
  • symmetric_difference(other)
  • symmetric_difference_update(other)
  • update(…)

frozenset

  • copy(…)
  • difference(…)
  • intersection(…)
  • isdisjoint(other)
  • issubset(other)
  • issuperset(other)
  • symmetric_difference(other)
  • union(…)

04 · Basics

Files, os and os.path

A program sees the files of its project as a folder. open() reads and writes text files; os and os.path list, check, rename and delete. Paths are relative to the project folder (/ is the project folder).

The files live in memory. Where they are kept permanently (folder, ZIP, browser storage) is up to the page that embeds Natter: it is told about every change (onFileChange).

Example
with open("noten.txt", "w") as f:
    f.write("Ada,1\nLinus,2\n")

with open("noten.txt") as f:
    for zeile in f:
        name, note = zeile.strip().split(",")
        print(name, "hat eine", note)

import os
print(os.listdir("."), os.path.getsize("noten.txt"))
Output
Ada hat eine 1
Linus hat eine 2
['noten.txt'] 14
File noten.txt
Ada,1
Linus,2

Limits and differences from CPython

  • Text files only (modes r, w, a, x, with +); "rb"/"wb" raise ValueError. The encoding is always UTF-8, line endings become \n.
  • os.environ is empty, os.getcwd() is "/"; os.walk works, os.path.getsize counts characters.
  • pathlib, shutil, csv and sqlite3 are missing (read CSV with split(",")).

open() and file objects

Functions

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Opens a text file. mode: "r" read, "w" write anew, "a" append, "x" create only, with + both.

Classes

  • TextFile(path, mode, encoding=None)
TextFile
read(size=-1)

Reads the rest (or size characters).

readline(size=-1)

Reads one line including \n.

readlines(hint=-1)

All lines as a list.

write(text)

Writes a string, returns the number of characters.

close()

Closes the file (with does it for you).

  • writelines(lines)
  • seek(offset, whence=0)
  • tell()
  • truncate(size=None)
  • flush()
  • readable()
  • writable()
  • seekable()

os

Functions

listdir(p='.')

Names in a folder (sorted).

remove(p)

Deletes a file.

mkdir(p, mode=511)

Creates a folder.

makedirs(p, mode=511, exist_ok=False)

Creates folders including the ones in between.

rename(a, b)

Renames or moves.

  • getcwd()
  • rmdir(p)
  • getenv(key, default=None)
  • walk(top)

Constants

  • sep= '/'
  • linesep= '\n'
  • name= 'posix'
  • curdir= '.'
  • pardir= '..'
  • environ= {}

os.path

Functions

exists(p)

Does the file or folder exist?

isfile(p)

Is it a file?

isdir(p)

Is it a folder?

join(a, *parts)

Joins path parts with /.

basename(p)

Last part of the path.

splitext(p)

Splits into name and extension.

  • split(p)
  • dirname(p)
  • normpath(p)
  • abspath(p)
  • isabs(p)
  • getsize(p)

Constants

  • sep= '/'
  • curdir= '.'
  • pardir= '..'

05 · Standard modules

math

import math

All functions of math used in school. They compute the same on every device: sin, exp, log … are implemented in Natter itself (after fdlibm, hypot and dist correctly rounded) instead of using the browser's functions, which differ in the last digit from device to device.

Example
import math
print(math.sqrt(2), math.pi)
print(math.sin(math.radians(30)), math.floor(-2.5), math.ceil(2.1))
print(math.gcd(12, 18), math.factorial(10), math.comb(49, 6))
print(math.hypot(3, 4), math.log(8, 2), math.isclose(0.1 + 0.2, 0.3))
Output
1.4142135623730951 3.141592653589793
0.49999999999999994 -3 3
6 3628800 13983816
5.0 3.0 True

Limits and differences from CPython

  • Results match CPython (apart from rare differences in the last digit for functions that CPython takes from the C library).

Functions

sqrt(x)

Square root.

sin(x)

Sine (radians).

cos(x)

Cosine (radians).

tan(x)

Tangent (radians).

asin(x)

Arc sine.

acos(x)

Arc cosine.

atan(x)

Arc tangent.

exp(x)

e to the power of x.

log2(x)

Base-2 logarithm.

log10(x)

Base-10 logarithm.

fabs(x)

Absolute value as a float.

degrees(x)

Radians to degrees.

radians(x)

Degrees to radians.

log(x, base=…)

Natural logarithm, or to base base.

pow(x, y)

Power as a float.

atan2(y, x)

Angle of the point (x, y), respecting the quadrant.

floor(x)

Round down to an integer.

ceil(x)

Round up to an integer.

trunc(x)

Cut off the decimals.

hypot(*coordinates)

Length of the vector (Pythagoras), correctly rounded.

dist(p, q)

Distance between two points.

isqrt(n)

Integer square root.

gcd(*integers)

Greatest common divisor.

lcm(*integers)

Least common multiple.

factorial(n)

Factorial n!.

comb(n, k)

Number of ways to choose k from n.

isclose(a, b)

Are two floats almost equal?

  • sinh(…)
  • cosh(…)
  • tanh(…)
  • asinh(…)
  • acosh(…)
  • atanh(…)
  • expm1(…)
  • exp2(…)
  • log1p(…)
  • cbrt(…)
  • perm(n, k=…)
  • prod(iterable, start=…)
  • fsum(iterable)
  • isfinite(x)
  • isinf(x)
  • isnan(x)
  • copysign(x, y)
  • fmod(x, y)
  • modf(x)
  • ldexp(x, i)

Constants

pi= 3.141592653589793

The number π.

e= 2.718281828459045

Euler's number.

inf= inf

Infinity.

  • tau= 6.283185307179586
  • nan= nan

06 · Standard modules

random

import random

Random numbers from the VM's own generator. Without a seed it starts from the browser's secure randomness, so every run differs; with random.seed(…) or a fixed seed from the page, every run is the same.

Example
import random
random.seed(7)
print(random.randint(1, 6), random.choice(["Stein", "Schere", "Papier"]))
karten = list(range(1, 11))
random.shuffle(karten)
print(karten, random.sample(karten, 3))
print(round(random.random(), 3), round(random.uniform(1, 2), 3))
Output
1 Papier
[3, 5, 6, 1, 10, 9, 2, 7, 4, 8] [1, 2, 3]
0.901 1.919

Limits and differences from CPython

  • The generator differs from CPython's (sfc32 instead of the Mersenne Twister): the same seed always gives the same numbers in Natter, but not the same as in CPython. (numpy.random, on the other hand, gives exactly numpy's numbers.)

Functions

random()

Float 0 ≤ x < 1.

randint(a, b)

Integer from a to b inclusive.

randrange(start, stop=…, step=…)

Random item of range(start, stop, step).

choice(seq)

One random item.

choices(population, weights=…, k=…)

k items with replacement, optionally weighted.

sample(population, k)

k different items without replacement.

shuffle(x)

Shuffles a list in place.

uniform(a, b)

Float between a and b.

gauss(mu=…, sigma=…)

Normally distributed with mean mu and deviation sigma.

seed(a=…)

Sets the seed (number or string; None: random).

  • triangular(low=…, high=…, mode=…)
  • expovariate(lambd)
  • getrandbits(k)
  • normalvariate(mu=…, sigma=…)

07 · Standard modules

time

import time

Clock and waiting. time.sleep() only pauses the program, never the page. In the page the clock is real; in test runs without a page a virtual clock runs and sleep takes no time.

Example
import time
start = time.perf_counter()
for i in range(3, 0, -1):
    print(i)
    time.sleep(0.5)
print("Los!", round(time.perf_counter() - start, 1), "Sekunden")
Output
3
2
1
Los! 1.5 Sekunden

Limits and differences from CPython

  • Time zone: localtime uses the browser's offset, timezone/tzname are fixed to 0/"UTC". strftime knows only English names (%A → Friday).

Functions

time()

Seconds since 1970 as a float.

perf_counter()

Precise clock for measuring time.

sleep(secs)

Waits secs seconds (the program, not the page).

localtime(secs=None)

Date and time as a tuple.

strftime(fmt, t=None)

Time as a string, e.g. "%H:%M".

  • time_ns(…)
  • monotonic(…)
  • process_time(…)
  • gmtime(secs=None)
  • mktime(t)
  • asctime(t=None)
  • ctime(secs=None)

Constants

  • timezone= 0
  • altzone= 0
  • daylight= 0
  • tzname= ('UTC', 'UTC')

08 · Standard modules

datetime

import datetime

Dates, times, time spans and fixed time zones, computed in the Gregorian calendar like CPython.

Example
from datetime import date, datetime, timedelta
ferien = date(2025, 7, 24)
heute = date(2025, 6, 2)
print((ferien - heute).days, "Tage bis zu den Ferien")
print(ferien.strftime("%d.%m.%Y"), ferien.weekday(), ferien + timedelta(weeks=6))
print(datetime(2025, 6, 2, 8, 15).isoformat())
Output
52 Tage bis zu den Ferien
24.07.2025 3 2025-09-04
2025-06-02T08:15:00

Limits and differences from CPython

  • datetime.now() uses the page's clock (in test runs the virtual clock: 1 January 2000). Month and day names in strftime are English only, there is no time zone database (zoneinfo is missing), only timezone(timedelta(…)).

Classes

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Time span; date ± time span gives a date.

timezone(offset, name=None)

Fixed time zone with an offset.

date(year, month, day)

A date (year, month, day).

time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

Time of day without a date.

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

Date with time.

  • tzinfo()
timedelta
  • total_seconds()
  • mintimedelta
  • maxtimedelta
  • resolutiontimedelta
date
  • today()classmethod
  • fromordinal(n)classmethod
  • fromtimestamp(ts)classmethod
  • fromisoformat(text)classmethod
  • toordinal()
  • weekday()
  • isoweekday()
  • isocalendar()
  • isoformat()
  • ctime()
  • strftime(fmt)
  • replace(year=None, month=None, day=None)
  • timetuple()
  • mindate
  • maxdate
  • resolutiontimedelta
time
  • isoformat(timespec='auto')
  • strftime(fmt)
  • replace(hour=None, minute=None, second=None, microsecond=None)
datetime
  • now(tz=None)classmethod
  • utcnow()classmethod
  • today()classmethod
  • fromtimestamp(ts, tz=None)classmethod
  • utcfromtimestamp(ts)classmethod
  • combine(d, t, tzinfo=None)classmethod
  • fromordinal(n)classmethod
  • strptime(text, fmt)classmethod
  • fromisoformat(text)classmethod
  • date()
  • time()
  • timestamp()
  • utcoffset()
  • tzname()
  • astimezone(tz=None)
  • replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=True)
  • isoformat(sep='T', timespec='auto')
  • ctime()
  • strftime(fmt)
  • timetuple()
  • mindatetime
  • maxdatetime

Inherited from date:

  • toordinal()
  • weekday()
  • isoweekday()
  • isocalendar()
  • resolutiontimedelta

Constants

  • MINYEAR= 1
  • MAXYEAR= 9999

09 · Standard modules

json

import json

Reading and writing JSON, formatted exactly like CPython (indent, sort_keys, ensure_ascii, separators).

Example
import json
daten = {"name": "Ada", "noten": [1, 2.5], "aktiv": True, "lehrer": None}
text = json.dumps(daten, indent=2, ensure_ascii=False)
print(text)
print(json.loads(text)["noten"][1])
Output
{
  "name": "Ada",
  "noten": [
    1,
    2.5
  ],
  "aktiv": true,
  "lehrer": null
}
2.5

Functions

dumps(obj, *, skipkeys=False, ensure_ascii=True, indent=None, separators=None, default=None, sort_keys=False)

Python value → JSON string.

loads(s, **kw)

JSON string → Python value.

dump(obj, fp, **kw)

Writes to an open file.

load(fp, **kw)

Reads from an open file.

Exceptions

  • JSONDecodeError(msg, doc, pos)

10 · Standard modules

statistics

import statistics

Mean, median, mode, variance and standard deviation.

Example
import statistics as st
noten = [2, 3, 1, 2, 4, 2]
print(st.mean(noten), st.median(noten), st.mode(noten))
print(round(st.stdev(noten), 3), st.multimode([1, 1, 2, 2]))
Output
2.3333333333333335 2.0 2
1.033 [1, 2]

Limits and differences from CPython

  • Computes with floats; there is no Fraction/Decimal. quantiles, correlation and linear_regression are missing (see numpy).

Functions

mean(data)

Arithmetic mean.

median(data)

Median (middle of the sorted values).

mode(data)

Most common value.

variance(data, xbar=None)

Sample variance.

pstdev(data, mu=None)

Population standard deviation.

stdev(data, xbar=None)

Sample standard deviation.

  • fmean(data, weights=None)
  • median_low(data)
  • median_high(data)
  • multimode(data)
  • pvariance(data, mu=None)

Exceptions

  • StatisticsError()

11 · Standard modules

collections

import collections

Counter, defaultdict, deque, OrderedDict and namedtuple.

Example
from collections import Counter, defaultdict, deque, namedtuple
print(Counter("abrakadabra").most_common(2))
gruppen = defaultdict(list)
for w in ["Apfel", "Birne", "Ananas"]:
    gruppen[w[0]].append(w)
print(dict(gruppen))
schlange = deque([1, 2, 3], maxlen=3)
schlange.append(4)
print(schlange)
Punkt = namedtuple("Punkt", "x y")
print(Punkt(2, 3).x)
Output
[('a', 5), ('b', 2)]
{'A': ['Apfel', 'Ananas'], 'B': ['Birne']}
deque([2, 3, 4], maxlen=3)
2

Limits and differences from CPython

  • The classes are written in Python and are not subclasses of dict: isinstance(Counter(), dict) is False. ChainMap and UserDict are missing.

Functions

namedtuple(typename, field_names, defaults=None)

Tuple class with named fields.

Classes

defaultdict(default_factory=None, *args)

Dict that creates missing keys with default_factory().

OrderedDict(*args, **kw)

Dict that can change its order.

Counter(iterable=None, **kw)

Counts items.

deque(iterable=(), maxlen=None)

Queue with fast appends and pops at both ends.

defaultdict
  • update(other=(), **kw)
  • copy()
OrderedDict
  • update(other=(), **kw)
  • move_to_end(key, last=True)
  • popitem(last=True)
Counter
  • update(iterable=None, **kw)
  • subtract(iterable=None, **kw)
  • most_common(n=None)
  • elements()
  • total()
  • copy()
deque
  • append(x)
  • appendleft(x)
  • pop()
  • popleft()
  • extend(iterable)
  • extendleft(iterable)
  • rotate(n=1)
  • clear()
  • count(x)
  • index(x)
  • remove(x)
  • reverse()
  • copy()

12 · Standard modules

itertools

import itertools

Building blocks for loops: combinatorics, endless sequences, grouping.

Example
import itertools
print(list(itertools.permutations("abc", 2)))
print(list(itertools.combinations(range(4), 2)))
for k, g in itertools.groupby("aaabbc"):
    print(k, len(list(g)), end=" ")
print()
print(list(itertools.islice(itertools.count(10, 5), 4)))
Output
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
a 3 b 2 c 1 
[10, 15, 20, 25]

Functions

count(start=0, step=1)

Counts forever.

cycle(iterable)

Repeats forever.

islice(iterable, *args)

Slice of an iterator.

accumulate(iterable, func=None, initial=None)

Running sums (or another function).

product(*iterables, repeat=1)

Cartesian product.

permutations(iterable, r=None)

All orderings.

combinations(iterable, r)

All selections without order.

groupby(iterable, key=None)

Groups of equal neighbours.

  • repeat(obj, times=None)
  • takewhile(predicate, iterable)
  • dropwhile(predicate, iterable)
  • filterfalse(predicate, iterable)
  • starmap(function, iterable)
  • compress(data, selectors)
  • zip_longest(*iterables, fillvalue=None)
  • pairwise(iterable)
  • combinations_with_replacement(iterable, r)
  • tee(iterable, n=2)

Classes

chain(*iterables)

Sequences one after another.

13 · Standard modules

functools

import functools

reduce, partial, lru_cache/cache, wraps, cmp_to_key, total_ordering.

Example
from functools import lru_cache, reduce, partial

@lru_cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(90))
print(reduce(lambda a, b: a * b, range(1, 6)))
zweier = partial(int, base=2)
print(zweier("1011"))
Output
2880067194370816120
120
11

Functions

reduce(function, iterable, *initial)

Combines a sequence into one value with a function.

lru_cache(maxsize=128, typed=False)

Remembers the results of a function (decorator).

cache(func)

Like lru_cache without a limit.

  • wraps(wrapped)
  • cmp_to_key(mycmp)
  • total_ordering(cls)

Classes

partial(func, *args, **keywords)

Function with some arguments already fixed.

14 · Standard modules

string

import string

Character classes as strings, and capwords.

Example
import string
print(string.ascii_uppercase)
print(string.capwords("hallo schöne welt"))
print(sum(1 for c in "Python 3.12!" if c in string.digits))
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Hallo Schöne Welt
3

Limits and differences from CPython

  • Template and Formatter are missing.

Functions

  • capwords(s, sep=None)

Constants

  • ascii_lowercase= 'abcdefghijklmnopqrstuvwxyz'
  • ascii_uppercase= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  • ascii_letters= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJK…
  • digits= '0123456789'
  • hexdigits= '0123456789abcdefABCDEF'
  • octdigits= '01234567'
  • punctuation= '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
  • whitespace= ' \t\n\r\x0b\x0c'
  • printable= '0123456789abcdefghijklmnopqrstuvwxyzA…

15 · Standard modules

copy

import copy

Shallow and deep copies of lists, dicts, sets and your own objects (respects __copy__/__deepcopy__).

Example
import copy
feld = [[0, 0], [0, 0]]
flach = copy.copy(feld)
tief = copy.deepcopy(feld)
feld[0][0] = 9
print(flach[0][0], tief[0][0])
Output
9 0

Functions

copy(x)

Shallow copy: the items themselves are shared.

deepcopy(x, memo=…)

Deep copy: all items are copied too.

16 · Standard modules

sys

import sys

The parts of sys that school programs need: exit, stdout/stderr/stdin, argv, version information.

Example
import sys
print(sys.version_info[:2], sys.platform)
sys.stdout.write("ohne Zeilenumbruch")
print()
if len(sys.argv) < 2:
    print("Keine Argumente, Ende.")
    sys.exit()
print("nie erreicht")
Output
(3, 12) browser
ohne Zeilenumbruch
Keine Argumente, Ende.

Limits and differences from CPython

  • setrecursionlimit has no effect (the limit is 1000), getsizeof always returns 64, sys.modules and sys.path are empty.

Functions

exit(code=None)

Ends the program (SystemExit).

  • getrecursionlimit()
  • setrecursionlimit(n)
  • getsizeof(obj)

Objects

stdout_Stream

Standard output (write, flush).

stderr_Stream

Error output.

stdin_Stream

Input (readline asks like input).

Constants

  • argv= ['']
  • maxsize= 9223372036854775807
  • version= '3.12.0 (Natter)'
  • version_info= (3, 12, 0, 'final', 0)
  • platform= 'browser'
  • byteorder= 'little'
  • path= []
  • modules= {}

17 · Standard modules

re

import re

Regular expressions with Python's syntax (named groups (?P<name>…), \A, \Z, lookbehind, flags, verbose mode). Positions count characters as in Python.

Example
import re
text = "Ada: 0171-555 12, Linus: 030 1234"
print(re.findall(r"\d+", text))
m = re.search(r"(?P<name>\w+): (?P<nr>[\d -]+)", text)
print(m.group("name"), m.span())
print(re.sub(r"\s+", " ", "viel    zu   viel Platz"))
print(re.split(r"[,:]\s*", text))
Output
['0171', '555', '12', '030', '1234']
Ada (0, 16)
viel zu viel Platz
['Ada', '0171-555 12', 'Linus', '030 1234']

Limits and differences from CPython

  • Runs on the browser's regex engine: possessive quantifiers, atomic groups and \G are missing; patterns with extreme backtracking can be slow.

Functions

compile(pattern, flags=0)

Compiled pattern for repeated use.

search(pattern, string, flags=0)

First match anywhere in the string (or None).

match(pattern, string, flags=0)

Match at the start only.

fullmatch(pattern, string, flags=0)

Does the pattern match the whole string?

findall(pattern, string, flags=0)

All matches as a list.

finditer(pattern, string, flags=0)

All matches as Match objects.

sub(pattern, repl, string, count=0, flags=0)

Replaces matches.

split(pattern, string, maxsplit=0, flags=0)

Splits at the matches.

  • subn(pattern, repl, string, count=0, flags=0)
  • escape(pattern)
  • purge()

Classes

  • Match(pattern, string, spans, pos, endpos)
  • Pattern(pattern, flags)
Match
  • group(*groups)
  • groups(default=None)
  • groupdict(default=None)
  • start(g=0)
  • end(g=0)
  • span(g=0)
  • expand(template)
Pattern
  • search(string, pos=0, endpos=None)
  • match(string, pos=0, endpos=None)
  • fullmatch(string, pos=0, endpos=None)
  • finditer(string, pos=0, endpos=None)
  • findall(string, pos=0, endpos=None)
  • subn(repl, string, count=0)
  • sub(repl, string, count=0)
  • split(string, maxsplit=0)

Exceptions

  • PatternError(msg, pattern=None, pos=None)
  • error(msg, pattern=None, pos=None)

Constants

  • I= 2
  • IGNORECASE= 2
  • L= 4
  • LOCALE= 4
  • M= 8
  • MULTILINE= 8
  • S= 16
  • DOTALL= 16
  • U= 32
  • UNICODE= 32
  • X= 64
  • VERBOSE= 64
  • A= 256
  • ASCII= 256
  • NOFLAG= 0

18 · Standard modules

pprint

import pprint

Prints nested data readably, with the same line-breaking rules as CPython.

Example
from pprint import pprint
schule = {"klassen": {"7a": ["Ada", "Linus", "Grace"], "7b": ["Alan", "Barbara"]}, "raeume": list(range(101, 112))}
pprint(schule, width=50)
Output
{'klassen': {'7a': ['Ada', 'Linus', 'Grace'],
             '7b': ['Alan', 'Barbara']},
 'raeume': [101,
            102,
            103,
            104,
            105,
            106,
            107,
            108,
            109,
            110,
            111]}

Functions

  • pformat(obj, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)
  • pprint(obj, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)
  • pp(obj, *args, sort_dicts=False, **kw)
  • saferepr(obj)
  • isreadable(obj)
  • isrecursive(obj)

Classes

  • PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

19 · Standard modules

textwrap

import textwrap

Wrapping, shortening and indenting text.

Example
import textwrap
satz = "Natter ist ein kleiner Python-Interpreter für den Unterricht im Browser."
print(textwrap.fill(satz, width=30))
print(textwrap.shorten(satz, width=30))
print(textwrap.indent("a\nb", "> "))
Output
Natter ist ein kleiner Python-
Interpreter für den Unterricht
im Browser.
Natter ist ein kleiner [...]
> a
> b

Functions

  • wrap(text, width=70, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')
  • fill(text, width=70, **kw)
  • shorten(text, width, **kw)
  • dedent(text)
  • indent(text, prefix, predicate=None)

Classes

  • TextWrapper(width=70, **kw)

20 · Drawing and games

turtle

import turtle

Turtle graphics as in CPython: the same formulas, so the same positions and headings. The page draws (origin in the middle, y up), animates according to speed() and sends keys, clicks and timers to mainloop().

Example
import turtle
t = turtle.Turtle()
t.speed(0)
t.color("darkgreen", "lightgreen")
t.begin_fill()
for i in range(5):
    t.forward(150)
    t.right(144)
t.end_fill()
t.penup()
t.goto(0, -60)
t.write("Stern", align="center", font=("Arial", 16, "bold"))
print(t.position(), t.heading())
turtle.done()
Output
(0.00,-60.00) 0.0

Limits and differences from CPython

  • No real Tk canvas: getcanvas()/cv return None; bgpic and shapes from image files only work if the page knows the image.
  • undo only undoes movements. Screen size before setup(): 960 × 810 like CPython, scaled down to the space on the page.

In the browser

  • Keys (Tk names like Left, space), clicks and taps reach onkey/onscreenclick once listen() and mainloop()/done() run; exitonclick() ends with the next click.
  • textinput/numinput open a dialog. The turtle shape is an image from the asset library, tinted with the fill colour.

Functions

reset()

Clears and resets.

clear()

Clears the turtle's drawing.

tracer(n=None, delay=None)

tracer(0) draws only on update() (fast).

forward(distance)

Moves forward.

back(distance)

Moves backward.

right(angle)

Turns right (degrees).

left(angle)

Turns left (degrees).

goto(x, y=None)

Moves to the point (x, y).

setheading(to_angle)

Heading in degrees (0 = right).

home()

Back to the centre, facing right.

circle(radius, extent=None, steps=None)

Circle or arc with a radius (counter-clockwise for a positive radius).

dot(size=None, *color)

Dot with diameter size.

stamp()

Leaves a print of the shape.

speed(speed=None)

1 (slow) to 10 (fast), 0 = no animation.

penup()

Lift the pen: draw nothing.

pendown()

Lower the pen: draw.

pensize(width=None)

Line width.

color(*args)

Pen and fill colour (names, #rrggbb or RGB).

begin_fill()

Starts a filled shape.

end_fill()

Fills the shape since begin_fill.

write(arg, move=False, align='left', font=('Arial', 8, 'normal'))

Writes text at the position.

hideturtle()

Hides the turtle.

shape(name=None)

Shape: turtle, arrow, circle, square, triangle, classic.

bgcolor(*args)

Background colour.

setup(width=0.5, height=0.75, startx=None, starty=None)

Window size.

mainloop()

Waits for events until the end.

done()

Same as mainloop.

onkey(fun, key)

Function for a key.

onscreenclick(fun, btn=1, add=None)

Function for clicks (gets x, y).

ontimer(fun, t=0)

Function after t milliseconds.

textinput(title, prompt)

Asks for a string (dialog).

numinput(title, prompt, default=None, minval=None, maxval=None)

Asks for a number (dialog).

setworldcoordinates(llx, lly, urx, ury)

Your own coordinate system.

  • getscreen()
  • getturtle()
  • getpen()
  • delay(delay=None)
  • screensize(*args)
  • onclick(fun, btn=1, add=None)
  • turtles()
  • clearscreen()
  • resetscreen()
  • fd(distance)
  • bk(distance)
  • backward(distance)
  • rt(angle)
  • lt(angle)
  • setpos(x, y=None)
  • setposition(x, y=None)
  • setx(x)
  • sety(y)
  • seth(to_angle)
  • clearstamp(stampid)
  • clearstamps(n=None)
  • pos()
  • position()
  • xcor()
  • ycor()
  • heading()
  • towards(x, y=None)
  • distance(x, y=None)
  • degrees(fullcircle=360.0)
  • radians()
  • pu()
  • up()
  • pd()
  • down()
  • isdown()
  • width(width=None)
  • pen(pen=None, **pendict)
  • pencolor(*args)
  • fillcolor(*args)
  • filling()
  • showturtle()
  • st()
  • ht()
  • isvisible()
  • shapesize(stretch_wid=None, stretch_len=None, outline=None)
  • turtlesize(stretch_wid=None, stretch_len=None, outline=None)
  • resizemode(rmode=None)
  • clone()
  • undo()
  • setundobuffer(size)
  • undobufferentries()
  • onrelease(fun, btn=1, add=None)
  • ondrag(fun, btn=1, add=None)
  • begin_poly()
  • end_poly()
  • get_poly()
  • teleport(x=None, y=None, fill_gap=False)
  • shearfactor(shear=None)
  • tilt(angle)
  • settiltangle(angle)
  • tiltangle(angle=None)
  • bgpic(picname=None)
  • title(titlestring)
  • window_width()
  • window_height()
  • update()
  • exitonclick()
  • bye()
  • mode(mode=None)
  • colormode(cmode=None)
  • listen(xdummy=None, ydummy=None)
  • onkeypress(fun, key=None)
  • onkeyrelease(fun, key)
  • register_shape(name, shape=None)
  • addshape(name, shape=None)
  • getshapes()

Classes

Turtle(shape='classic', undobuffersize=1000, visible=True)

A new turtle (several are possible).

Screen()

The drawing area (background, size, events).

  • RawTurtle(shape='classic', undobuffersize=1000, visible=True)
Turtle
  • teleport(x=None, y=None, fill_gap=False)
  • speed(speed=None)
  • penup()
  • pendown()
  • isdown()
  • pensize(width=None)
  • pen(pen=None, **pendict)
  • pencolor(*args)
  • fillcolor(*args)
  • color(*args)
  • filling()
  • begin_fill()
  • end_fill()
  • dot(size=None, *color)
  • stamp()
  • clearstamp(stampid)
  • clearstamps(n=None)
  • write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
  • showturtle()
  • hideturtle()
  • isvisible()
  • shape(name=None)
  • shapesize(stretch_wid=None, stretch_len=None, outline=None)
  • turtlesize(stretch_wid=None, stretch_len=None, outline=None)
  • pu()
  • up()
  • pd()
  • down()
  • width(width=None)
  • st()
  • ht()
  • resizemode(rmode=None)
  • shearfactor(shear=None)
  • tilt(angle)
  • settiltangle(angle)
  • tiltangle(angle=None)
  • clear()
  • reset()
  • clone()
  • undo()
  • setundobuffer(size)
  • undobufferentries()
  • begin_poly()
  • end_poly()
  • get_poly()
  • getscreen()
  • getturtle()
  • getpen()
  • onclick(fun, btn=1, add=None)
  • onrelease(fun, btn=1, add=None)
  • ondrag(fun, btn=1, add=None)
  • tracer(n=None, delay=None)
  • delay(delay=None)
  • screensize(*args)

Inherited from TNavigator:

  • degrees(fullcircle=360.0)
  • radians()
  • forward(distance)
  • back(distance)
  • right(angle)
  • left(angle)
  • pos()
  • xcor()
  • ycor()
  • goto(x, y=None)
  • home()
  • setx(x)
  • sety(y)
  • distance(x, y=None)
  • towards(x, y=None)
  • heading()
  • setheading(to_angle)
  • circle(radius, extent=None, steps=None)
  • fd(distance)
  • bk(distance)
  • backward(distance)
  • rt(angle)
  • lt(angle)
  • position()
  • setpos(x, y=None)
  • setposition(x, y=None)
  • seth(to_angle)
Screen
  • bgcolor(*args)
  • bgpic(picname=None)
  • title(titlestring)
  • setup(width=0.5, height=0.75, startx=None, starty=None)
  • screensize(canvwidth=None, canvheight=None, bg=None)
  • window_width()
  • window_height()
  • tracer(n=None, delay=None)
  • delay(delay=None)
  • update()
  • mode(mode=None)
  • colormode(cmode=None)
  • register_shape(name, shape=None)
  • addshape(name, shape=None)
  • getshapes()
  • turtles()
  • clearscreen()
  • clear()
  • resetscreen()
  • reset()
  • listen(xdummy=None, ydummy=None)
  • onkey(fun, key)
  • onkeyrelease(fun, key)
  • onkeypress(fun, key=None)
  • onscreenclick(fun, btn=1, add=None)
  • onclick(fun, btn=1, add=None)
  • ontimer(fun, t=0)
  • textinput(title, prompt)
  • numinput(title, prompt, default=None, minval=None, maxval=None)
  • mainloop()
  • done()
  • exitonclick()
  • bye()
  • setworldcoordinates(llx, lly, urx, ury)
  • cv()
  • getcanvas()

Exceptions

  • TurtleGraphicsError()
  • Terminator()

21 · Drawing and games

Kara the ladybug

import kara (or no import)

Kara walks on a meadow of cells, collects blueberries, avoids trees and pushes mushrooms. The commands are named as in the book (move, turnLeft, treeFront …) and work with import kara (kara.move()), with from kara import * or without any import: when a program starts with world("""…"""), the commands are already there.

The meadow is a picture made of characters, one line of text per row. Kara faces right at the start. Lines may differ in length (missing cells are empty).

Example: Collecting the berries in a row
world("""
########
#@ . ..#
########
""")

while not treeFront():
    if onBerry():
        removeBerry()
    move()
if onBerry():
    removeBerry()
Meadow at the end
########
#     @#
########

Limits and differences from CPython

  • treeFront(), treeLeft() and treeRight() are also true at the edge of the meadow (the edge acts like a tree).
  • Mushrooms can be pushed like crates in Sokoban: move() against a mushroom pushes it one cell further if the cell behind is free (no tree, no mushroom, no edge). The usual goal is to push all mushrooms onto berries (*).

In the browser

  • The page draws with the images of the kara pack of the asset library and animates every step (0.3 s by default). Without the library it draws simple shapes.

Commands

world(text)

Sets up the meadow (characters below). Must come before all other commands.

move()

One cell forward (pushes a mushroom).

turnLeft()

Quarter turn to the left.

turnRight()

Quarter turn to the right.

putBerry()

Puts a blueberry on the cell.

removeBerry()

Picks up the blueberry from the cell.

onBerry()

Is Kara on a blueberry?

treeFront()

Is there a tree (or the edge) in front?

treeLeft()

Is there a tree (or the edge) on the left?

treeRight()

Is there a tree (or the edge) on the right?

mushroomFront()

Is there a mushroom in front?

World characters

CharacterMeaning
#tree
.blueberry
$mushroom
*mushroom on a blueberry
@Kara (facing right)
+Kara on a blueberry
␣empty cell

Error messages

  • tree Kara bumped her head on a tree.
  • edge Kara reached the edge of the meadow and cannot go further.
  • mushroom The mushroom cannot be pushed: behind it is a tree, a mushroom or the edge.
  • berryThere There is already a blueberry here.
  • noBerry There is no blueberry here to pick up.
  • noWorld There is no meadow yet. Call world("""...""") first.
  • noKara The meadow has no Kara (the character @ or +).
  • twoKaras The meadow has more than one Kara.
  • badChar The character “{char}” does not exist in the meadow (line {y}, column {x}).

22 · Drawing and games

Pygame Zero

import pgzrun (or no import)

Games with the API of Pygame Zero 1.2: write draw() and update(), move Actors, read keys, play sounds. The game logic computes like the real Pygame Zero (compared with pgzero 1.2.1 and pygame 2), plus the popular extensions from pgzhelper (scale, flip_x, images/animate, move_towards …).

A game starts like pgzrun game.py: if the program has def draw() or def update() (or WIDTH/HEIGHT and Actor/screen), it knows all the names below without an import. With import pgzrun and pgzrun.go() at the end it works the same; code after go() runs when the window is closed.

Window: WIDTH, HEIGHT (default 800 × 600) and TITLE as global variables. Images are found by their name without extension: first in the project folder images/ (sounds sounds/, music music/, fonts fonts/), then in the asset library.

Example: Collecting coins
import random

WIDTH = 480
HEIGHT = 320
TITLE = "Münzjagd"

heldin = Actor("heroine_idle_1", (240, 260))
muenze = Actor("pf_coin_1", (100, 80))
punkte = 0

def draw():
    screen.fill("skyblue")
    heldin.draw()
    muenze.draw()
    screen.draw.text("Punkte: " + str(punkte), (10, 10), fontsize=32, color="white")

def update():
    global punkte
    if keyboard.left:
        heldin.x -= 5
    if keyboard.right:
        heldin.x += 5
    muenze.y += 2
    if heldin.colliderect(muenze):
        punkte += 1
        sounds.coin.play()
        neu()
    elif muenze.top > HEIGHT:
        neu()

def neu():
    muenze.pos = (random.randint(20, WIDTH - 20), -20)

def on_mouse_down(pos):
    heldin.x = pos[0]

The images heroine_idle_1, pf_coin_1 and the sound coin come from the asset library, without uploading any files.

Limits and differences from CPython

  • keys, keymods and mouse are plain numbers instead of IntEnum (print is the same, repr differs).
  • Callbacks of clock stay alive (Pygame Zero forgets lambda callbacks); an error in a callback stops the game with an error message.
  • Image subfolders only via images.load("folder/name"). Missing: music.get_pos, pixel, circle and OBB collisions and sprite sheets of pgzhelper, screen.surface (always None).

In the browser

  • Fixed rate: 60 frames per second (update(dt) with dt = 1/60), at most 4 frames are caught up; a hidden tab pauses. If a frame needs too many instructions (endless loop), the game ends with the line of the loop.
  • Sound only after the first touch, click or key press (a browser rule); until then the game shows a hint to tap or click for sound.
  • On phones a finger acts like the left mouse button; the page can show a button bar (◀ ▶ ▲ ▼, jump = space).

Hooks (functions you write)

def draw()

Draws the picture. Runs after update and after events; the canvas is not cleared automatically (screen.clear() or screen.fill()).

def update(dt)

Game logic, 60 times per second. dt (seconds passed) may be left out.

def on_mouse_down(pos, button)

Mouse button pressed or finger down; button is mouse.LEFT, mouse.RIGHT …

def on_mouse_up(pos, button)

Mouse button released.

def on_mouse_move(pos, buttons, rel)

Mouse moved; rel is the movement, buttons the pressed buttons.

def on_key_down(unicode, key, mod)

Key pressed; key is e.g. keys.SPACE, unicode the character.

def on_key_up(key, mod)

Key released.

def on_music_end()

A music track has ended.

Predefined names

Actor(image, pos=None, anchor=None, **kwargs)

A game character made from an image: position (x, y, pos, center, topleft …), angle, scale, collisions, draw().

Rect(*args)

Rectangle with integers like pygame.Rect.

ZRect(*args)

Rectangle with floats.

animate(object, tween='linear', duration=1, on_finished=None, **targets)

Animates attributes: animate(figure, pos=(100, 50), duration=1, tween="bounce_end").

clock

Timers: clock.schedule(f, 2.0), clock.schedule_interval(f, 1.0).

keyboardKeyboard

Pressed keys: keyboard.left, keyboard.space, keyboard.a, keyboard[keys.LEFT].

keys_Enum

Key codes (keys.LEFT, keys.SPACE, keys.A …).

keymods_Enum

Modifier keys (keymods.SHIFT …).

mouse_Enum

Mouse buttons (mouse.LEFT …).

music_Music

Background music: music.play("name").

soundsSoundLoader

Sounds by name: sounds.coin.play().

imagesImageLoader

Images by name: images.pf_coin_1 (for blit and sizes).

tone_Tone

Generates tones: tone.play("A4", 0.5).

screenScreen

The canvas: fill, clear, blit and the drawing commands in screen.draw.

exit()

Ends the game.

Actor
angleproperty

Rotation in degrees.

scaleproperty

Scaling factor (pgzhelper).

opacityproperty

Opacity 0 to 1.

imageproperty

Name of the image (assigning changes the image).

posproperty

Position of the anchor (default: centre).

colliderect(a=…, b=…, c=…, d=…)

Does it overlap a rectangle or another actor?

collidepoint(a=…, b=…)

Is the point inside the actor?

draw()

Draws the actor.

angle_to(target)

Angle to a point or actor (degrees, counter-clockwise).

distance_to(target)

Distance to a point or actor.

move_towards(target, dist, stop_on_target=True)

Moves dist towards the target (pgzhelper).

point_towards(target)

Turns towards the target (pgzhelper).

imagesproperty

List of image names for next_image()/animate() (pgzhelper).

  • fps= 5
  • direction= 0
  • anchorproperty
  • flip_xproperty
  • flip_yproperty
  • xproperty
  • yproperty
  • rect()
  • leftproperty
  • topproperty
  • widthproperty
  • heightproperty
  • rightproperty
  • bottomproperty
  • topleftproperty
  • centerproperty
  • centerxproperty
  • centeryproperty
  • sizeproperty
  • collidelist(others)
  • collidelistall(others)
  • contains(*other)
  • direction_to(target)
  • move_in_direction(dist)
  • move_forward(dist)
  • move_back(dist)
  • move_left(dist)
  • move_right(dist)
  • next_image()
  • sel_image(newimage)
  • animate()
  • toprightproperty
  • bottomleftproperty
  • bottomrightproperty
  • midtopproperty
  • midleftproperty
  • midbottomproperty
  • midrightproperty
  • clamp(*args, **kwargs)
  • clamp_ip(*args, **kwargs)
  • clip(*args, **kwargs)
  • clip_ip(*args, **kwargs)
  • collidedict(*args, **kwargs)
  • collidedictall(*args, **kwargs)
  • copy(*args, **kwargs)
  • fit(*args, **kwargs)
  • inflate(*args, **kwargs)
  • inflate_ip(*args, **kwargs)
  • move(*args, **kwargs)
  • move_ip(*args, **kwargs)
  • normalize(*args, **kwargs)
  • union(*args, **kwargs)
  • union_ip(*args, **kwargs)
  • unionall(*args, **kwargs)
  • unionall_ip(*args, **kwargs)
Rect
  • xproperty
  • leftproperty
  • yproperty
  • topproperty
  • wproperty
  • widthproperty
  • hproperty
  • heightproperty
  • rightproperty
  • bottomproperty
  • centerxproperty
  • centeryproperty
  • topleftproperty
  • toprightproperty
  • bottomleftproperty
  • bottomrightproperty
  • midtopproperty
  • midleftproperty
  • midbottomproperty
  • midrightproperty
  • centerproperty
  • sizeproperty
  • copy()
  • normalize()
  • move(*args)
  • move_ip(*args)
  • inflate(*args)
  • inflate_ip(*args)
  • scale_by(*args, **kw)
  • scale_by_ip(*args, **kw)
  • update(*args)
  • union(*args)
  • union_ip(*args)
  • unionall(rect)
  • unionall_ip(rects)
  • clamp(*args)
  • clamp_ip(*args)
  • clip(*args)
  • clipline(*args, **kw)
  • fit(*args)
  • contains(*args)
  • collidepoint(a=…, b=…)
  • colliderect(a=…, b=…, c=…, d=…)
  • collidelist(rects)
  • collidelistall(rects)
  • collideobjects(objects, key=None)
  • collideobjectsall(objects, key=None)
  • collidedict(rect_dict, values=0)
  • collidedictall(rect_dict, values=0)
ZRect
  • copy()
  • widthproperty
  • heightproperty
  • topproperty
  • leftproperty
  • rightproperty
  • bottomproperty
  • centerxproperty
  • centeryproperty
  • topleftproperty
  • toprightproperty
  • bottomleftproperty
  • bottomrightproperty
  • midtopproperty
  • midleftproperty
  • midbottomproperty
  • midrightproperty
  • centerproperty
  • sizeproperty
  • move(x, y)
  • move_ip(x, y)
  • inflate(x, y)
  • inflate_ip(x, y)
  • clamp(*other)
  • clamp_ip(*other)
  • clip(*other)
  • clip_ip(*other)
  • union(*other)
  • union_ip(*other)
  • unionall(others)
  • unionall_ip(others)
  • fit(*other)
  • normalize()
  • contains(*other)
  • collidepoint(*args)
  • colliderect(a=…, b=…, c=…, d=…)
  • collidelist(others)
  • collidelistall(others)
  • collidedict(dict, use_values=True)
  • collidedictall(dict, use_values=True)
clock
  • tick(dt)
  • schedule(callback, delay)
  • schedule_interval(callback, delay)
  • schedule_unique(callback, delay)
  • unschedule(callback)
  • each_tick(callback)
keys
  • keys.AC_BACK
  • keys.UNKNOWN
  • keys.BACKSPACE
  • keys.TAB
  • keys.CLEAR
  • keys.RETURN
  • keys.PAUSE
  • keys.ESCAPE
  • keys.SPACE
  • keys.QUOTE
  • keys.COMMA
  • keys.MINUS
  • keys.PERIOD
  • keys.SLASH
  • keys.K_0
  • keys.K_1
  • keys.K_2
  • keys.K_3
  • keys.K_4
  • keys.K_5
  • keys.K_6
  • keys.K_7
  • keys.K_8
  • keys.K_9
  • keys.SEMICOLON
  • keys.EQUALS
  • keys.LEFTBRACKET
  • keys.BACKSLASH
  • keys.RIGHTBRACKET
  • keys.BACKQUOTE
  • keys.A
  • keys.B
  • keys.C
  • keys.D
  • keys.E
  • keys.F
  • keys.G
  • keys.H
  • keys.I
  • keys.J
  • keys.K
  • keys.L
  • keys.M
  • keys.N
  • keys.O
  • keys.P
  • keys.Q
  • keys.R
  • keys.S
  • keys.T
  • keys.U
  • keys.V
  • keys.W
  • keys.X
  • keys.Y
  • keys.Z
  • keys.DELETE
  • keys.KP_0
  • keys.KP_1
  • keys.KP_2
  • keys.KP_3
  • keys.KP_4
  • keys.KP_5
  • keys.KP_6
  • keys.KP_7
  • keys.KP_8
  • keys.KP_9
  • keys.KP0
  • keys.KP1
  • keys.KP2
  • keys.KP3
  • keys.KP4
  • keys.KP5
  • keys.KP6
  • keys.KP7
  • keys.KP8
  • keys.KP9
  • keys.KP_PERIOD
  • keys.KP_DIVIDE
  • keys.KP_MULTIPLY
  • keys.KP_MINUS
  • keys.KP_PLUS
  • keys.KP_ENTER
  • keys.KP_EQUALS
  • keys.UP
  • keys.DOWN
  • keys.RIGHT
  • keys.LEFT
  • keys.INSERT
  • keys.HOME
  • keys.END
  • keys.PAGEUP
  • keys.PAGEDOWN
  • keys.F1
  • keys.F2
  • keys.F3
  • keys.F4
  • keys.F5
  • keys.F6
  • keys.F7
  • keys.F8
  • keys.F9
  • keys.F10
  • keys.F11
  • keys.F12
  • keys.F13
  • keys.F14
  • keys.F15
  • keys.NUMLOCKCLEAR
  • keys.NUMLOCK
  • keys.CAPSLOCK
  • keys.SCROLLLOCK
  • keys.SCROLLOCK
  • keys.RSHIFT
  • keys.LSHIFT
  • keys.RCTRL
  • keys.LCTRL
  • keys.RALT
  • keys.LALT
  • keys.RGUI
  • keys.RMETA
  • keys.LGUI
  • keys.LMETA
  • keys.LSUPER
  • keys.RSUPER
  • keys.MODE
  • keys.HELP
  • keys.PRINTSCREEN
  • keys.PRINT
  • keys.SYSREQ
  • keys.BREAK
  • keys.MENU
  • keys.POWER
  • keys.CURRENCYUNIT
  • keys.CURRENCYSUBUNIT
  • keys.EURO
  • keys.EXCLAIM
  • keys.QUOTEDBL
  • keys.HASH
  • keys.DOLLAR
  • keys.AMPERSAND
  • keys.PERCENT
  • keys.LEFTPAREN
  • keys.RIGHTPAREN
  • keys.ASTERISK
  • keys.PLUS
  • keys.COLON
  • keys.LESS
  • keys.GREATER
  • keys.QUESTION
  • keys.AT
  • keys.CARET
  • keys.UNDERSCORE
keymods
  • keymods.NONE
  • keymods.LSHIFT
  • keymods.RSHIFT
  • keymods.LCTRL
  • keymods.RCTRL
  • keymods.LALT
  • keymods.RALT
  • keymods.LGUI
  • keymods.RGUI
  • keymods.NUM
  • keymods.CAPS
  • keymods.MODE
  • keymods.CTRL
  • keymods.SHIFT
  • keymods.ALT
  • keymods.GUI
  • keymods.LMETA
  • keymods.RMETA
  • keymods.META
mouse
  • mouse.LEFT
  • mouse.MIDDLE
  • mouse.RIGHT
  • mouse.WHEEL_UP
  • mouse.WHEEL_DOWN
music
play(name)

Plays a track in a loop.

play_once(name)

Plays a track once.

fadeout(seconds)

Fades out over seconds.

stop()

Stops the music.

set_volume(value)

Volume 0 to 1.

  • queue(name)
  • is_playing(name=None)
  • pause()
  • unpause()
  • rewind()
  • set_pos(pos)
  • get_volume()
sounds

Inherited from ResourceLoader:

  • load(name)
images

Inherited from ResourceLoader:

  • load(name)
tone
  • InvalidNote()
  • create(pitch, duration)
  • play(pitch, duration)
  • note_to_hertz(note)
screen
clear()

Makes the canvas black.

fill(color, gcolor=None)

Fills with a colour (name, (r, g, b) or #rrggbb), with gcolor as a gradient.

blit(image, pos)

Draws an image at pos (top-left corner).

  • bounds()
  • drawread-only
screen.draw
line(start, end, color, width=1)

Line from start to end.

circle(pos, radius, color, width=1)

Circle outline.

filled_circle(pos, radius, color)

Filled circle.

rect(rect, color, width=1)

Rectangle outline.

filled_rect(rect, color)

Filled rectangle.

text(*args, **kwargs)

Text at pos (or center=, topright= …) with fontsize, color, width, align, owidth/ocolor (outline), shadow, gcolor, alpha, angle like ptext.

textbox(*args, **kwargs)

Text as large as possible inside a rectangle.

  • polygon(points, color)
  • filled_polygon(points, color)
Sound
play(loops=0, maxtime=0, fade_ms=0)

Plays the sound (loops, maxtime, fade_ms).

stop()

Stops the sound.

set_volume(value)

Volume 0 to 1.

  • fadeout(time)
  • get_volume()
  • get_length()
  • get_num_channels()

23 · Drawing and games

Asset library

About 900 images in one consistent style plus short sounds, free to use (CC0). A program only names them, without uploading files: Actor("heroine_run_1"), screen.blit("pf_grass_mid", (0, 416)), sounds.coin.play(). Kara and the turtle shape use the same library.

Only what the program mentions is loaded. A string like "heroine_run_" + str(i) loads all images whose name starts that way. Your own file with the same name in the project folder images/ wins. The sprite gallery shows all images and sounds with previews, sorted by game type; the packs live in packages/assets (gametypes.json, catalog.json).

Names

  • Lower case, ASCII, unique across all packs. Animation frames end in _1, _2 … (heroine_run_1 to heroine_run_8); characters face right unless the name says _left. Names in the book pack are German (ente, kueken, boot) because the book uses them.

Game types with starter sets

Game typePacks and starter images
Platformer
platformer
Run, jump, collect coins – seen from the side
Packs: platformer characters
heroine_run_1 heroine_idle_1 heroine_jump enemy_walk_1 slug_walk_1 pf_grass_left pf_grass_mid pf_grass_right pf_crate pf_spikes pf_spring_1 pf_coin_1 pf_gem_blue pf_flag_1 pf_bg_day
Space
space
Spaceship, aliens, asteroids and lasers
Packs: space
sp_ship sp_ship_fire_1 sp_enemy_1 sp_alien sp_ufo sp_boss sp_asteroid_m sp_asteroid_l sp_laser_blue sp_bullet sp_explosion_1 sp_power_shield sp_planet_1 sp_bg_space
Sea
sea
Boats, fish and treasure under water
Packs: sea
sea_submarine sea_pirate_ship sea_sailboat sea_fish_1 sea_fish_2 sea_shark sea_jellyfish sea_octopus sea_crab sea_starfish sea_chest sea_bubble sea_coral_1 sea_bg
Nature & garden
nature
Trees, flowers, fruit, vegetables and weather
Packs: nature
nat_oak nat_pine nat_apple_tree nat_bush nat_sunflower nat_tulip nat_mushroom_brown nat_rock_1 nat_seedling nat_carrot fruit_apple fruit_strawberry nat_sun nat_cloud_1 nat_raindrop
Animals
animals
Pets and wild animals, and a pet to look after
Packs: animals
an_cat an_dog an_rabbit an_duck an_chicken an_cow an_pig an_horse an_frog an_owl an_penguin an_bee_1 an_butterfly_1 pet_cat_happy pet_food_bowl
Flyers & falling things
flyer
Fly through gaps or catch what falls
Packs: flyer
fl_bird_1 fl_plane fl_balloon fl_dragon_1 fl_pillar_top fl_pillar_bottom fl_cloud_obstacle fl_coin_1 fl_star fl_ground fl_bg_day fall_basket fall_apple fall_bomb
Arcade
arcade
Snake, Pong, Breakout, car racing and target throwing
Packs: arcade
snake_head_right snake_body snake_apple pong_paddle pong_ball breakout_paddle brick_red block_cyan car_red car_police cone balloon_red target cannon maze_player
Puzzles & board games
puzzle
Chess, checkers, 2048, dice, memory and tic-tac-toe
Packs: grid_puzzle arcade
chess_king_w chess_knight_b chess_square_light chess_square_dark check_red check_black_king num_tile_2 num_tile_2048 life_alive dice_6 ttt_x ttt_o c4_red memory_back memory_star
Top-down & grid games
grid
Push crates, bombs, tower defense, farm, frog across the road, mines, pipes
Packs: grid_chars grid_tiles grid_action grid_puzzle
robo_down_1 fuchs_down_1 gp_floor gp_wall gp_crate gp_target bomb_1 bomb_blast_center td_tower_arrow_1 td_enemy_1 farm_carrot_4 cross_frog_up cross_car_1 ms_hidden pipe_corner_ne_wet gt_key_red
Adventure
adventure
Hero, monsters, tiles and treasure – seen from above
Packs: adventure
hero_girl_down_1 hero_boy_down_1 npc_wizard mon_slime_1 mon_ghost mon_dragon tile_grass tile_path tile_water tile_wall tile_door_closed adv_chest_closed adv_key adv_sword adv_potion_red adv_heart
Duck, Kara & turtle
book
Duck, chick and boat of the book, Kara the ladybug, the turtle
Packs: book kara turtle
ente ente_links kueken boot seerose frosch fisch_1 teich_hintergrund kara kara_blueberry kara_tree kara_mushroom turtle
Interface
ui
Hearts, score digits, buttons, bars and speech bubbles
Packs: ui
ui_heart_full ui_heart_empty ui_star_full ui_coin ui_trophy ui_0 ui_play ui_pause ui_restart ui_sound_on ui_button_green ui_panel ui_speech_bubble ui_bar_green ui_arrow_left ui_dpad

Browse all images and sounds in the sprite gallery

Packs

  • adventure Adventure
  • animals Animals
  • arcade Arcade
  • book Pond game of the book
  • characters Characters
  • flyer Flyers and falling things
  • grid_action Grid action
  • grid_chars Grid characters (top-down)
  • grid_puzzle Grid puzzles and board games
  • grid_tiles Grid tiles
  • kara Kara the ladybug
  • nature Nature and weather
  • platformer Platformer
  • sea Sea
  • space Space
  • turtle Turtle
  • ui Game interface
  • sounds Sounds

Sounds

  • sounds.platsch Water splash
  • sounds.coin Collect a coin
  • sounds.jump Jump
  • sounds.hit Hit
  • sounds.explosion Explosion
  • sounds.laser Laser shot
  • sounds.powerup Power up
  • sounds.click Click
  • sounds.blip Blip
  • sounds.win You win
  • sounds.lose You lose
  • sounds.bounce Bounce
  • sounds.step Footstep
  • sounds.quack Quack

24 · Forms, data, network

Forms with guizero

from guizero import App, Text, PushButtonPack guizero

Windows with buttons, text boxes and lists through the API of guizero 1.6. Programs run as the guizero documentation shows them; defaults, warnings and error messages match the real guizero.

The page draws the widgets as real HTML elements. Layout auto works like Tk pack, layout grid is a grid that grows with its content (grid=[column, row], also [column, row, width, height]).

Example: Counter
from guizero import App, Text, PushButton, Box

app = App(title="Zähler", width=240, height=160)
anzeige = Text(app, text="0", size=40)
knoepfe = Box(app, layout="grid")

def plus():
    anzeige.value = int(anzeige.value) + 1

def null():
    anzeige.value = 0

PushButton(knoepfe, text="+1", command=plus, grid=[0, 0])
PushButton(knoepfe, text="Null", command=null, grid=[1, 0])
app.display()

Limits and differences from CPython

  • No tkinter behind it: .tk is a small stand-in, add_tk_widget does not work. Errors in callbacks end the program (Tk would only print them).
  • Images (Picture, PushButton(image=…), Drawing.image) come from the project files: PNG, GIF, JPEG, BMP, WebP, SVG.

In the browser

  • On narrow screens windows fill the width and several windows become tabs. Sizes as in guizero: text widgets in characters and lines, containers and windows in pixels.
  • Dialogs (info, yesno, question, select_file, select_color …) appear as a card over the windows; select_file shows the project's files. Timers (after, repeat) run in real time.

Functions

info(title, text, master=None)

Message with OK.

yesno(title, text, master=None)

Yes/no question, returns True/False.

question(title, question, initial_value=None, master=None)

Asks for a string.

select_file(title='Select file', folder='.', filetypes=[['All files', '*.*']], save=False, master=None, filename='')

Choose a file of the project.

select_color(color=None, master=None)

Choose a colour.

  • warn(title, text, master=None)
  • error(title, text, master=None)
  • select_folder(title='Select folder', folder='.', master=None)

Classes

App(title='guizero', width=500, height=500, layout='auto', bg=None, visible=True)

The main window; display() shows it and waits for events.

Window(master, title='guizero', width=500, height=500, layout='auto', bg=None, visible=True)

Another window.

Box(master, layout='auto', grid=None, align=None, visible=True, enabled=None, width=None, height=None, border=None)

Invisible container for grouping.

TitleBox(master, text, layout='auto', grid=None, align=None, visible=True, enabled=None, width=None, height=None, border=2)

Container with a border and title.

Text(master, text='', size=None, color=None, bg=None, font=None, grid=None, align=None, visible=True, enabled=None, width=None, height=None, bold=None, italic=None, underline=None, overstrike=None)

A text (value).

TextBox(master, text='', width=10, height=1, grid=None, align=None, visible=True, enabled=None, multiline=False, scrollbar=False, command=None, hide_text=False)

Input field (value, multiline, hide_text for passwords).

PushButton(master, command=None, args=None, text='Button', image=None, pady=10, padx=10, grid=None, align=None, icon=None, visible=True, enabled=None, width=None, height=None)

Button; command is called on click.

CheckBox(master, text='', command=None, grid=None, align=None, args=None, visible=True, enabled=None, width=None, height=None)

Box to tick (value 0/1).

ButtonGroup(master, options=[], selected=None, horizontal=False, command=None, grid=None, align=None, args=None, visible=True, enabled=None, width=None, height=None)

Choice among options (radio buttons).

Combo(master, options=[], selected=None, command=None, grid=None, align=None, visible=True, enabled=None, width=None, height=None)

Drop-down list.

ListBox(master, items=None, selected=None, command=None, grid=None, align=None, visible=True, enabled=None, multiselect=False, scrollbar=False, width=None, height=None)

List, also with multiple selection.

Slider(master, start=0, end=100, horizontal=True, command=None, grid=None, align=None, visible=True, enabled=None, width=None, height=None, step=1)

Slider.

Picture(master, image=None, grid=None, align=None, visible=True, enabled=None, width=None, height=None)

An image from the project.

Waffle(master, height=3, width=3, dim=20, pad=5, color='white', dotty=False, grid=None, align=None, command=None, visible=True, enabled=None, bg=None)

Grid of cells, e.g. for pixel pictures and games.

Drawing(master, width=100, height=100, grid=None, align=None, visible=True, enabled=None)

Drawing area: lines, ovals, rectangles, polygons, text, images.

MenuBar(master, toplevel, options)

Menu bar.

App
  • display()
  • destroy()
Window
  • hide()
  • show(wait=False)
Box
  • borderproperty
  • set_border(thickness, color='black')
  • resize(width, height)
TitleBox
  • borderproperty
  • textproperty
  • resize(width, height)
Text
  • valueproperty
  • sizeproperty
  • boldproperty
  • italicproperty
  • underlineproperty
  • overstrikeproperty
  • descriptionread-only
  • clear()
  • append(text)
TextBox
  • valueproperty
  • resize(width, height)
  • hide_textproperty
  • descriptionread-only
  • cursor_positionproperty
  • wrapproperty
  • update_command(command)
  • clear()
  • append(text)
PushButton
  • valueread-only
  • textproperty
  • imageproperty
  • descriptionread-only
  • padding(padx, pady)
  • toggle()
  • update_command(command, args=None)
  • resize(width, height)
CheckBox
  • valueproperty
  • textproperty
  • descriptionread-only
  • toggle()
  • update_command(command, args=None)
ButtonGroup
  • valueproperty
  • value_textproperty
  • resize(width, height)
  • optionsread-only
  • descriptionread-only
  • append(option)
  • insert(index, option)
  • remove(option)
  • clear()
  • get_group_as_list()
  • update_command(command, args=None)
Combo
  • valueproperty
  • optionsread-only
  • descriptionread-only
  • select_default()
  • append(option)
  • insert(index, option)
  • remove(option)
  • clear()
  • update_command(command)
ListBox
  • resize(width, height)
  • valueproperty
  • insert(index, item)
  • append(item)
  • remove(item)
  • clear()
  • itemsread-only
  • update_command(command)
Slider
  • valueproperty
  • startproperty
  • endproperty
  • stepproperty
  • resize(width, height)
  • descriptionread-only
  • update_command(command)
Picture
  • valueproperty
  • imageproperty
  • resize(width, height)
Waffle
  • set_all(color)
  • set_pixel(x, y, color)
  • get_pixel(x, y)
  • get_all()
  • update_command(command)
  • pixel(x, y)
  • disable()
  • enable()
  • resize(width, height)
  • pixel_sizeproperty
  • padproperty
  • colorproperty
  • dottyproperty
  • descriptionread-only
  • reset()
Drawing
  • line(x1, y1, x2, y2, color='black', width=1)
  • oval(x1, y1, x2, y2, color='black', outline=False, outline_color='black')
  • rectangle(x1, y1, x2, y2, color='black', outline=False, outline_color='black')
  • polygon(*coords, color='black', outline=False, outline_color='black')
  • triangle(x1, y1, x2, y2, x3, y3, color='black', outline=False, outline_color='black')
  • image(x, y, image, width=None, height=None)
  • text(x, y, text, color='black', font=None, size=None, max_width=None, bold=None, italic=None, underline=None, overstrike=None)
  • delete(id)
  • clear()

Exceptions

  • GUIZeroException()
All widgets also have
  • after(time, function, args=[])
  • repeat(time, function, args=[])
  • cancel(function)
  • destroy()
  • enabledproperty
  • disable()
  • enable()
  • focus()
  • visibleproperty
  • hide()
  • show()
  • bgproperty
  • widthproperty
  • heightproperty
  • resize(width, height)
  • gridproperty
  • alignproperty
  • when_clickedproperty
  • when_double_clickedproperty
  • when_left_button_pressedproperty
  • when_left_button_releasedproperty
  • when_right_button_pressedproperty
  • when_right_button_releasedproperty
  • when_key_pressedproperty
  • when_key_releasedproperty
  • when_mouse_entersproperty
  • when_mouse_leavesproperty
  • when_mouse_movedproperty
  • when_mouse_draggedproperty
  • masterread-only
  • descriptionread-only
  • eventsread-only
  • displayableread-only
  • when_resizedproperty

25 · Forms, data, network

numpy

import numpy as npPack numpy

An honest subset of numpy 2: arrays with broadcasting, arithmetic, statistics, sorting, random numbers, some linear algebra. What exists prints the same digits as numpy (compared with numpy 2.5): output format, statistics and numpy.random with the same seed.

dtypes: int64, float64, bool and strings. Slices and .T are views as in numpy (changing them changes the original); mask and list indexes return copies.

Example
import numpy as np
a = np.arange(1, 7).reshape(2, 3)
print(a)
print(a.sum(axis=0), a.mean(), a[a > 2])
x = np.linspace(0, 1, 5)
print(x ** 2, np.round(np.sin(x), 3))
rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=5))
Output
[[1 2 3]
 [4 5 6]]
[5 7 9] 3.5 [3 4 5 6]
[0.     0.0625 0.25   0.5625 1.    ] [0.    0.247 0.479 0.682 0.841]
[1 5 4 3 3]

Limits and differences from CPython

  • Results without an axis (a.sum(), a[0]) are Python numbers, not numpy scalars: print is the same, repr inside lists differs, a.sum() / 0 is a ZeroDivisionError.
  • Missing: complex numbers, real 32-bit types (int32, float32 become 64 bit), object and structured arrays, several axes at once, ... as an index, out=/where=, np.fft, linalg.eig/svd/lstsq, file I/O (loadtxt, save), split, roll, pad.
  • Warnings like RuntimeWarning: divide by zero appear once per line in the error output and the program goes on (like numpy).

numpy

Functions

array(object, dtype=…, copy=…, order=…, subok=…, ndmin=…)

Array from a (nested) list.

zeros(shape, dtype=…)

Array of zeros.

ones(shape, dtype=…)

Array of ones.

arange(start=…, stop=…, step=…, dtype=…)

Like range, as an array (also floats).

linspace(start, stop, num=…, endpoint=…, retstep=…, dtype=…)

num evenly spaced values from start to stop.

reshape(a, shape)

New shape, same data.

where(condition, x=…, y=…)

Chooses element-wise from x or y.

sum(a, axis=None, keepdims=False)

Sum (pairwise like numpy, same digits).

mean(a, axis=None)

Mean.

std(a, axis=None, ddof=0)

Standard deviation.

sort(a, axis=…, kind=…)

Sorted copy (stable).

unique(ar, return_index=…, return_inverse=…, return_counts=…, axis=…)

Sorted distinct values, optionally with counts.

histogram(a, bins=…, range=…, density=…, weights=…)

Counts in bins.

dot(a, b, out=…)

Dot product / matrix product (also a @ b).

polyfit(x, y, deg)

Least-squares polynomial of degree deg.

sqrt(x)

Square root per element (correctly rounded).

sin(x)

Sine per element.

  • asarray(a, dtype=…, order=…)
  • copy(a)
  • empty(shape, dtype=…)
  • full(shape, fill_value, dtype=…)
  • zeros_like(a, dtype=…)
  • ones_like(a, dtype=…)
  • empty_like(a, dtype=…)
  • full_like(a, fill_value, dtype=…)
  • eye(N, M=…, k=…, dtype=…)
  • identity(n, dtype=…)
  • meshgrid(x, y)
  • ravel(a)
  • transpose(a, axes=…)
  • shape(a)
  • size(a)
  • ndim(a)
  • squeeze(a, axis=…)
  • expand_dims(a, axis)
  • concatenate(arrays, axis=…)
  • vstack(tup)
  • hstack(tup)
  • column_stack(tup)
  • stack(arrays, axis=…)
  • append(arr, values, axis=…)
  • flip(m, axis=…)
  • repeat(a, repeats, axis=…)
  • tile(A, reps)
  • nonzero(a)
  • argwhere(a)
  • clip(a, a_min, a_max, out=…)
  • maximum(x1, x2)
  • minimum(x1, x2)
  • arctan2(x1, x2)
  • hypot(x1, x2)
  • logical_and(x1, x2)
  • logical_or(x1, x2)
  • logical_xor(x1, x2)
  • isclose(a, b, rtol=…, atol=…, equal_nan=…)
  • allclose(a, b, rtol=…, atol=…, equal_nan=…)
  • array_equal(a1, a2, equal_nan=…)
  • round(a, decimals=…, out=…)
  • power(x1, x2)
  • add(x1, x2)
  • subtract(x1, x2)
  • multiply(x1, x2)
  • divide(x1, x2)
  • floor_divide(x1, x2)
  • mod(x1, x2)
  • prod(…)
  • min(…)
  • max(…)
  • any(…)
  • all(…)
  • ptp(…)
  • count_nonzero(…)
  • amin(…)
  • amax(…)
  • argmin(…)
  • argmax(…)
  • var(…)
  • cumsum(…)
  • cumprod(…)
  • nansum(a, axis=…, dtype=…, out=…, keepdims=…)
  • nanmean(a, axis=…, dtype=…, out=…, keepdims=…)
  • nanvar(a, axis=…, dtype=…, out=…, ddof=…, keepdims=…)
  • nanstd(a, axis=…, dtype=…, out=…, ddof=…, keepdims=…)
  • nanmax(a, axis=…, out=…, keepdims=…)
  • nanmin(a, axis=…, out=…, keepdims=…)
  • nanmedian(a, axis=…)
  • median(a, axis=…)
  • percentile(a, q, axis=…)
  • quantile(a, q, axis=…)
  • average(a, axis=…, weights=…)
  • diff(a, n=…, axis=…)
  • argsort(a, axis=…, kind=…)
  • bincount(x, weights=…, minlength=…)
  • matmul(x1, x2)
  • outer(a, b)
  • trace(a)
  • diag(v, k=…)
  • polyval(p, x)
  • corrcoef(x, y=…)
  • cov(m, y=…)
  • interp(x, xp, fp)
  • isscalar(…)
  • set_printoptions(precision=…, threshold=…, edgeitems=…, linewidth=…, suppress=…, nanstr=…, infstr=…, formatter=…, sign=…, floatmode=…, legacy=…)
  • get_printoptions(…)
  • exp(…)
  • exp2(…)
  • expm1(…)
  • log(…)
  • log2(…)
  • log10(…)
  • log1p(…)
  • cos(…)
  • tan(…)
  • arcsin(…)
  • arccos(…)
  • arctan(…)
  • sinh(…)
  • cosh(…)
  • tanh(…)
  • arcsinh(…)
  • arccosh(…)
  • arctanh(…)
  • degrees(…)
  • radians(…)
  • rad2deg(…)
  • deg2rad(…)
  • absolute(…)
  • fabs(…)
  • negative(…)
  • positive(…)
  • floor(…)
  • ceil(…)
  • trunc(…)
  • rint(…)
  • fix(…)
  • sign(…)
  • square(…)
  • reciprocal(…)
  • cbrt(…)
  • isnan(…)
  • isinf(…)
  • isfinite(…)
  • logical_not(…)
  • signbit(…)
  • abs(…)
  • around(a, decimals=…, out=…)
  • vectorize(pyfunc, otypes=None)
  • apply_along_axis(func1d, axis, arr)
  • fromfunction(function, shape, dtype=…)

Classes

  • ndarray(shape, dtype=…)
ndarray
  • reshape(…)
  • flatten(…)
  • ravel(…)
  • copy(…)
  • tolist(…)
  • item(…)
  • astype(dtype, order=…, casting=…, subok=…, copy=…)
  • fill(…)
  • transpose(…)
  • sort(axis=…, kind=…)
  • argsort(…)
  • sum(…)
  • prod(…)
  • mean(…)
  • min(…)
  • max(…)
  • std(…)
  • var(…)
  • argmin(…)
  • argmax(…)
  • cumsum(…)
  • cumprod(…)
  • any(…)
  • all(…)
  • ptp(…)
  • clip(…)
  • dot(…)
  • nonzero(…)
  • squeeze(…)
  • trace(…)
  • diagonal(…)
  • round(…)
  • shaperead-only
  • sizeread-only
  • ndimread-only
  • dtyperead-only
  • flatread-only
  • itemsizeread-only
  • nbytesread-only

Constants

  • pi= 3.141592653589793
  • e= 2.718281828459045
  • euler_gamma= 0.5772156649015329
  • inf= inf
  • nan= nan
  • newaxis= None

numpy.random

Functions

default_rng(seed=…)

New random generator (PCG64) – with a seed, the same numbers as numpy.

seed(seed)

Seed of the legacy generator (MT19937 like numpy).

rand(d0, d1, …)

Uniform numbers in [0, 1).

randint(low, high=None, size=None)

Random integers from low to below high.

normal(loc=0.0, scale=1.0, size=None)

Normally distributed numbers.

  • randn(…)
  • random_sample(…)
  • ranf(…)
  • sample(…)
  • random_integers(…)
  • uniform(…)
  • standard_normal(…)
  • exponential(…)
  • poisson(…)
  • binomial(…)
  • choice(…)
  • shuffle(…)
  • permutation(…)

Classes

  • RandomState()
  • Generator()

numpy.linalg

Functions

det(a)

Determinant.

inv(a)

Inverse matrix.

solve(a, b)

Solves the linear system a x = b.

  • norm(x, ord=None, axis=None)

Exceptions

  • LinAlgError()

26 · Forms, data, network

Plots with matplotlib.pyplot

import matplotlib.pyplot as pltPack pyplot

Function graphs, scatter plots, bars, histograms and pie charts like matplotlib 3: the same axes, ticks, colours, legends and positions. plt.show() shows the plot as SVG in the page and the program goes on at once; plt.savefig("plot.svg") offers it for download.

The object-oriented style works too: fig, ax = plt.subplots(), ax.plot(…), axs[0, 1], ax.set(title=…).

Example
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), "r--", label="cos")
plt.title("Sinus und Kosinus")
plt.xlabel("x")
plt.legend()
plt.grid(True)
plt.show()
Image (drawn by Natter)
0 1 2 3 4 5 6 −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 x Sinus und Kosinus sin cos

Natter drew the image below while this page was built.

Limits and differences from CPython

  • Always SVG (even savefig("plot.png") holds SVG). Missing: logarithmic axes, imshow, contour, colorbar, boxplot, polar and 3-D axes, twinx, colormaps (except viridis for scatter(c=…)), rcParams, animations; the placeholders below raise NotImplementedError with a tip.
  • Maths in text is basic only: $x^2$, $t_0$, Greek letters. tight_layout() does nothing.

Functions

figure(figsize=(6.4, 4.8), dpi=100)

New figure (640 × 480 pixels by default).

subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, figsize=None, dpi=None, **kwargs)

Figure with a grid of axes: fig, axs = plt.subplots(2, 2).

show(*args, **kwargs)

Shows the open figures.

savefig(fname, **kwargs)

Saves the figure (as SVG).

plot(x, y, fmt="", **kwargs)

Lines and markers; format strings like "r--o", color, linewidth, marker, label.

scatter(x, y, s=None, c=None, **kwargs)

Scatter plot, colour and size per point.

bar(x, height, width=0.8, **kwargs)

Bar chart, categories as strings.

barh(y, width, **kwargs)

Horizontal bar chart.

hist(x, bins=10, **kwargs)

Histogram (bins, density, cumulative, histtype).

pie(x, labels=None, autopct=None, **kwargs)

Pie chart.

axhline(y=0, xmin=0, xmax=1, **kwargs)

Horizontal line.

axvline(x=0, ymin=0, ymax=1, **kwargs)

Vertical line.

text(x, y, s, **kwargs)

Text at a position.

annotate(text, xy, xytext=None, **kwargs)

Text with an arrow.

title(label, **kwargs)

Title.

xlabel(xlabel, **kwargs)

Label of the x axis.

ylabel(ylabel, **kwargs)

Label of the y axis.

xlim(*args, **kwargs)

Range of the x axis.

ylim(*args, **kwargs)

Range of the y axis.

legend(*args, **kwargs)

Legend from the labels (loc="best" like matplotlib).

grid(visible=None, which='major', axis='both', **kwargs)

Grid lines.

  • gcf(…)
  • gca(…)
  • sca(…)
  • close(…)
  • clf(…)
  • subplot(*args, **kwargs)
  • errorbar(*args, **kwargs)
  • fill_between(*args, **kwargs)
  • suptitle(t, **kwargs)
  • xticks(ticks=None, labels=None, **kwargs)
  • yticks(ticks=None, labels=None, **kwargs)
  • axis(*args, **kwargs)
  • tight_layout(**kwargs)
  • subplots_adjust(**kwargs)
  • cla()
  • get_fignums()
  • ion()
  • ioff()
  • pause(interval)

Classes

  • Figure()
  • Axes()
Figure
  • add_subplot(…)
  • gca(…)
  • suptitle(…)
  • tight_layout(…)
  • subplots_adjust(…)
  • set_size_inches(…)
  • set_facecolor(…)
  • get_axes(…)
  • savefig(…)
  • show(…)
  • axesread-only
Axes
  • plot(…)
  • scatter(…)
  • bar(…)
  • barh(…)
  • hist(…)
  • pie(…)
  • axhline(…)
  • axvline(…)
  • fill_between(…)
  • errorbar(…)
  • text(…)
  • annotate(…)
  • set_title(…)
  • get_title(…)
  • set_xlabel(…)
  • set_ylabel(…)
  • get_xlabel(…)
  • get_ylabel(…)
  • set_xlim(…)
  • set_ylim(…)
  • get_xlim(…)
  • get_ylim(…)
  • set_xticks(…)
  • set_yticks(…)
  • set_xticklabels(…)
  • set_yticklabels(…)
  • get_xticks(…)
  • get_yticks(…)
  • legend(…)
  • grid(…)
  • set_aspect(…)
  • axis(…)
  • set_axis_off(…)
  • set_axis_on(…)
  • tick_params(…)
  • cla(…)
  • set_facecolor(…)
  • get_figure(…)
  • set(…)

Placeholders only (raise NotImplementedError)

  • xscale(*args, **kwargs)
  • yscale(*args, **kwargs)
  • semilogx(*args, **kwargs)
  • semilogy(*args, **kwargs)
  • loglog(*args, **kwargs)
  • imshow(*args, **kwargs)
  • contour(*args, **kwargs)
  • contourf(*args, **kwargs)
  • colorbar(*args, **kwargs)
  • boxplot(*args, **kwargs)
  • violinplot(*args, **kwargs)
  • stem(*args, **kwargs)
  • step(*args, **kwargs)
  • quiver(*args, **kwargs)
  • polar(*args, **kwargs)
  • stackplot(*args, **kwargs)
  • twinx(*args, **kwargs)

27 · Forms, data, network

requests and CORS

import requests

Fetching data from the web as with the requests package: requests.get(url).json(). The page performs the request with fetch; the program waits meanwhile.

Why some addresses fail (CORS): a browser only lets a web page read answers from servers that explicitly allow it (header Access-Control-Allow-Origin). Open data APIs such as Open-Meteo, Wikipedia and many JSON APIs allow it; ordinary web pages usually do not. When the browser blocks a request, Natter raises ConnectionError with exactly this explanation. Remedies: use a source that allows CORS, put the data into the project as a file, or run the program on your own computer with CPython.

Example
import requests

antwort = requests.get("https://api.open-meteo.com/v1/forecast", params={
    "latitude": 52.52, "longitude": 13.41, "current_weather": "true"})
antwort.raise_for_status()
wetter = antwort.json()["current_weather"]
print("Berlin:", wetter["temperature"], "°C, Wind", wetter["windspeed"], "km/h")

Limits and differences from CPython

  • Text only: response.content (bytes), file uploads, streaming and cookies are missing. Only http:// and https://; timeout 30 s when timeout is not given.
  • Headers that browsers forbid (User-Agent, Cookie …) are silently dropped by them.

Functions

request(method, url, params=None, data=None, headers=None, json=None, timeout=None, auth=None, allow_redirects=True, **kw)

Request with any method.

get(url, params=None, **kw)

GET request; params are appended to the address.

post(url, data=None, json=None, **kw)

POST request with form data (data) or JSON (json).

  • put(url, data=None, **kw)
  • patch(url, data=None, **kw)
  • delete(url, **kw)
  • head(url, **kw)

Classes

Response(status, reason, headers, text, url)

Answer: status_code, ok, text, json(), headers, url.

Session()

Shared headers and parameters for several requests.

Response
okread-only

Status below 400?

json(**kw)

Answer text parsed as JSON.

raise_for_status()

Raises HTTPError if the status is an error.

  • contentread-only
  • iter_lines()
Session
  • request(method, url, **kw)
  • get(url, **kw)
  • post(url, **kw)
  • close()

Exceptions

ConnectionError(*args, **kwargs)

Server unreachable or blocked by the browser (CORS).

Timeout(*args, **kwargs)

No answer in time.

HTTPError(*args, **kwargs)

Raised by raise_for_status() for status 400 to 599.

  • RequestException(*args, **kwargs)
  • ConnectTimeout(*args, **kwargs)
  • ReadTimeout(*args, **kwargs)
  • InvalidURL(*args, **kwargs)
  • MissingSchema(*args, **kwargs)
  • JSONDecodeError(msg, doc, pos)

This page is generated from the Natter source (npm run reference, scripts/build-reference.mjs): names, parameters, constants, error messages and image names come from the interpreter itself, and every example ran while the page was built. A test fails when the page no longer matches the code.