Command reference
Every command you need on CodeNatter for Turtle, Kara, games, windows, charts and more – explained in short. Open any example with “Open in the editor” and run it there.
Input and output #
With print() your program shows something in the console, with input() it asks. input() always returns text: wrap it in int() or float() for numbers. time.sleep() makes the program wait.
Console
print(value, …)Prints values, separated by spaces. sep=", " changes the separator, end="" leaves out the line break.input("Question: ")Waits until a line has been typed and returns it as text. The input line appears below the output.int(text)Turns text into a whole number: int(input("Age? ")).float(text)Turns text into a decimal number (with a point: 3.5).str(number)Turns a number into text, for example to join it: "Points: " + str(p).f"Hello {name}"f-string: values in curly braces end up in the text.Waiting and chance
time.sleep(seconds)Waits that many seconds (also 0.5). The page stays usable meanwhile, Stop always works.time.time()Seconds since 1970 – the difference of two values measures a time.random.randint(a, b)A random whole number from a to b (both included).random.choice(list)A random element of the list.random.random()A random decimal number from 0 to just below 1.Example: Ask for the age
Open in the editor ↗age = int(input("How old are you? "))
print("In 10 years you will be", age + 10)
Example: Countdown with sleep
Open in the editor ↗import time
for i in range(5, 0, -1):
print(i)
time.sleep(1)
print("Go!")
Turtle #
A turtle with a pen walks across the canvas and draws. The commands are the same as in Python’s turtle module. The center is (0, 0), y grows upwards.
Moving
t = turtle.Turtle()Creates a turtle. Several are allowed.t.forward(distance)Walks forward (short t.fd). t.back(distance) walks back.t.left(angle)Turns left, t.right(angle) turns right (in degrees).t.goto(x, y)Goes straight to the point (x, y), drawing a line if the pen is down.t.setheading(angle)Sets the direction: 0 right, 90 up, 180 left, 270 down.t.circle(radius)Draws a circle; t.circle(50, 180) only a half circle.t.home()Back to the center, facing right.t.speed(0)Speed 1 (slow) to 10, 0 = instant.Pen and color
t.penup()Pen up: move without drawing. t.pendown() puts it down again.t.pencolor("red")Pen color: an English color name or "#ff8800".t.pensize(width)Line width in pixels.t.fillcolor("gold")Fill color for begin_fill()/end_fill(). t.color("red", "gold") sets both.t.begin_fill()From here on the drawn shape is remembered, t.end_fill() fills it.t.dot(size, "blue")A round dot at the current position.t.write("Text")Writes text at the current position, for example with font=("Arial", 16, "bold").t.hideturtle()Hides the turtle, t.showturtle() shows it again.turtle.bgcolor("black")Background color of the canvas.Keys and clicks
turtle.onkey(function, "Left")Calls the function when the key is pressed ("Up", "space", "a" …). Call turtle.listen() first.turtle.onscreenclick(function)Calls function(x, y) on a click or tap.turtle.ontimer(function, ms)Calls the function once after that many milliseconds.turtle.done()Waits for keys and clicks until you press Stop (also turtle.mainloop()).Example: Filled square
Open in the editor ↗import turtle
t = turtle.Turtle()
t.color("darkgreen", "lightgreen")
t.begin_fill()
for i in range(4):
t.forward(100)
t.left(90)
t.end_fill()
Example: Draw with the arrow keys
Open in the editor ↗import turtle
t = turtle.Turtle()
t.speed(0)
def left():
t.left(15)
def right():
t.right(15)
def ahead():
t.forward(10)
turtle.listen()
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(ahead, "Up")
turtle.done()
Kara #
Kara is a ladybug on a meadow. You paint the world with characters in world("""…"""), the commands come without an import (as in the book). At the start Kara looks to the right.
The world
world("""…""")Builds the world from characters: @ Kara, # tree, . berry, $ mushroom, * mushroom on a berry, + Kara on a berry, space = meadow.Acting
move()One cell forward. If a mushroom is in front, Kara pushes it along when there is room behind it (like crates in Sokoban).turnLeft()Turns left on the spot.turnRight()Turns right on the spot.putBerry()Puts down a berry (only where there is none yet).removeBerry()Eats the berry beneath her.Sensing (True or False)
onBerry()Am I sitting on a berry?treeFront()Is there a tree (or the edge) in front of me?treeLeft()Is there a tree to my left?treeRight()Is there a tree to my right?mushroomFront()Is there a mushroom in front of me?- If Kara walks into a tree or the edge, eats a berry where there is none, or pushes a mushroom against an obstacle, the program stops with an error message.
- Sokoban idea: bring every mushroom
$onto a berry – then it shows*. Mushrooms can only be pushed, not pulled.
Example: Walk to the tree
Open in the editor ↗world("""
#########
#@ . . #
#########
""")
while not treeFront():
if onBerry():
removeBerry()
move()
Example: Sokoban: mushroom onto the berry
Open in the editor ↗world("""
#######
#@ $ .#
#######
""")
while not mushroomFront():
move()
move()
move()
print("Done: the mushroom is on the berry.")
Games with Pygame Zero #
A game starts with import pgzrun and ends with pgzrun.go(). In between you set the size and write functions that the game calls by itself: draw() draws, update() moves (about 60 times a second). On a phone, arrow and jump buttons appear below the game.
Skeleton
WIDTH = 800Width of the playing field in pixels, HEIGHT the height, TITLE the title.def draw():Draws the picture again. Usually screen.clear() or a background first.def update():Moves everything a little bit, about 60 times a second.def on_key_down(key):Called once per key press: if key == keys.SPACE:.def on_mouse_down(pos):A click or tap; pos is (x, y). Also on_mouse_up(pos) and on_mouse_move(pos).pgzrun.go()Starts the game. Must be the last line.Characters (Actor)
actor = Actor("ente", (x, y))A character with an image from the image library; the position is its center.actor.x, actor.yPosition of the center; changing it moves the character. Also actor.pos = (x, y).actor.draw()Draws the character (in draw()).actor.image = "ente_links"Changes the image, for example for an animation.actor.angleRotation in degrees, counterclockwise.actor.colliderect(other)Do two characters touch?actor.collidepoint(pos)Is the point (a click, say) on the character?actor.left, .right, .top, .bottomEdges of the character, handy for the edge of the field.actor.distance_to(other)Distance in pixels; actor.move_towards(target, 3) moves a bit towards it.Drawing (screen)
screen.clear()Makes everything black.screen.fill("skyblue")Fills with a color (a name or (r, g, b)).screen.blit("pf_bg_day", (0, 0))Draws an image with its top left corner at (x, y), for example a background.screen.draw.text("Hello", (10, 10))Writes text, for example with fontsize=40, color="white".screen.draw.filled_circle((x, y), r, "red")A filled circle; screen.draw.circle only the outline.screen.draw.filled_rect(Rect(x, y, w, h), "blue")A filled rectangle; screen.draw.rect only the outline.screen.draw.line((x1, y1), (x2, y2), "white")A line.Keyboard, time, sounds
keyboard.leftIs the key held down right now? Also keyboard.right, keyboard.up, keyboard.space, keyboard.a …keys.SPACEKey names for on_key_down(key): keys.LEFT, keys.RETURN, keys.A …clock.schedule_interval(function, seconds)Calls the function again and again; clock.schedule(function, 2) once after 2 seconds.animate(actor, pos=(x, y), duration=1)Moves a character smoothly to the target.sounds.coin.play()Plays a sound from the library: coin, jump, hit, laser, explosion, win, platsch …tone.play("C4", 0.5)Plays a tone (note, duration in seconds).- Sound only plays after the first click or key press – that is what browsers want.
Example: Duck with the arrow keys
Open in the editor ↗import pgzrun
WIDTH = 480
HEIGHT = 320
duck = Actor("ente", (240, 160))
def draw():
screen.fill("lightblue")
duck.draw()
def update():
if keyboard.left:
duck.x = duck.x - 4
if keyboard.right:
duck.x = duck.x + 4
pgzrun.go()
Example: Click the coin
Open in the editor ↗import pgzrun
import random
WIDTH = 480
HEIGHT = 320
points = 0
coin = Actor("pf_coin_1", (240, 160))
def draw():
screen.fill("darkgreen")
coin.draw()
screen.draw.text("Points: " + str(points), (10, 10), fontsize=32)
def on_mouse_down(pos):
global points
if coin.collidepoint(pos):
points = points + 1
sounds.coin.play()
coin.pos = (random.randint(30, 450), random.randint(30, 290))
pgzrun.go()
Image library #
Every game finds about 600 images and 14 sounds just by their names – you do not have to upload anything. The gallery shows all images with search, preview and ready-made code.To the image gallery →
Using images
Actor("ente")An image as a game character. The images of the book have German names: ente (duck), kueken (duckling), boot (boat).images.heroine_run_1An image as an object, for example for screen.blit(images.pf_grass_mid, (0, 400))."heroine_run_" + str(i)The frames of an animation are called thing_action_1, thing_action_2 … Shown one after another, they move.pf_ sp_ sea_ nat_ an_ ui_The beginning tells the pack: platformer, space, sea, nature, animals, game interface.images/ente.pngIn the expert mode a file of your own in the folder images/ wins over the library image of the same name.Example: Running heroine (animation)
Open in the editor ↗import pgzrun
WIDTH = 480
HEIGHT = 320
RUN = ["heroine_run_" + str(i) for i in range(1, 9)]
heroine = Actor(RUN[0], (240, 200))
time = 0
def draw():
screen.blit("pf_bg_day", (0, 0))
heroine.draw()
def update():
global time
time = time + 1
heroine.image = RUN[time // 4 % 8]
pgzrun.go()
Windows with guizero #
With guizero you build windows with texts, input fields and buttons. A button calls a function through command=. At the end there is always app.display().
Window and widgets
app = App(title="My window")The main window; also width=, height=, bg=, layout="grid".Text(app, text="Hello")A text; size=, color=, font=. Change it with label.value = "New".TextBox(app)An input field; the typed text is in box.value.PushButton(app, text="OK", command=function)A button that calls the function (no parentheses after it!).CheckBox(app, text="Yes")A check box, box.value is 1 or 0.Combo(app, options=["a", "b"])A drop-down list; the choice is in .value.Slider(app, start=0, end=100)A slider with its number in .value.ListBox(app, items=[…])A list to choose from.Box(app, layout="grid")Groups widgets, for example buttons side by side (align="left") or in a grid (grid=[column, row]).Picture(app, image="picture.png")Shows an image from the project.Drawing(app)A drawing area: .rectangle(), .oval(), .line(), .text().Waffle(app)A grid of colored cells, good for small games.Window(app)A second window; .show() and .hide().Flow
app.display()Shows the window and waits for clicks. Must be at the end.app.repeat(1000, function)Calls the function every second (clock, game); app.after(ms, function) once.app.info("Title", "Text")A message box; app.yesno(…) asks yes/no, app.question(…) asks for text.widget.when_clicked = functionReacts to clicks on any widget; function(event) gets event.x, event.y.Form designer
Code | DesignIf guizero is in the program, “Code | Design” appears above the code box. In the design you drag widgets into the window and change their properties – the code writes itself along.Double-click a buttonCreates the function for command= in the code and jumps there. “← Back to the design” takes you back.TestStarts the window in the design the way it looks when it runs.Example: Greeting
Open in the editor ↗from guizero import App, Text, TextBox, PushButton
app = App(title="Greeting", width=300, height=180)
name = TextBox(app)
answer = Text(app, text="")
def greet():
answer.value = "Hello " + name.value + "!"
PushButton(app, text="Greet", command=greet)
app.display()
Example: Seconds counter
Open in the editor ↗from guizero import App, Text
app = App(title="Clock", width=240, height=140)
display = Text(app, text="0", size=40)
def tick():
display.value = int(display.value) + 1
app.repeat(1000, tick)
app.display()
Calculating with numpy #
numpy calculates with whole rows of numbers (arrays) at once: a * 2 doubles every number. Natter brings the most important parts.
Arrays
np.array([1, 2, 3])An array from a list.np.arange(0, 10, 2)Numbers from 0 to below 10 in steps of two.np.linspace(0, 1, 5)5 evenly spaced numbers from 0 to 1 – good for graphs of functions.np.zeros(5)An array of zeros; np.ones(5) of ones.a + b, a * 2, a ** 2Calculate with every element at once.a[a > 2]Only the elements that meet the condition.a.shapeShape of the array, for example (3,) or (2, 3); a.reshape(2, 3) changes it.Evaluating
a.sum()Sum; also a.mean() (average), a.min(), a.max(), a.std().np.median(a)Median (middle value).np.sqrt(a)Square root of every element; also np.sin, np.cos, np.exp, np.log.np.piThe number π.np.random.randint(1, 7, 100)100 random numbers from 1 to 6 (7 is not included).np.unique(a, return_counts=True)The different values and how often they occur.Example: Average score
Open in the editor ↗import numpy as np
scores = np.array([72, 85, 90, 64, 78, 88, 95])
print("Average:", scores.mean())
print("Best score:", scores.max())
print("Above 80:", scores[scores > 80])
Charts with matplotlib #
With matplotlib.pyplot you draw charts. plt.show() shows them next to the code; below every chart there are buttons to download it as SVG or PNG.
Kinds of charts
plt.plot(x, y)A line chart; "r--" makes a red dashed line, label="…" for the legend.plt.scatter(x, y)A scatter plot.plt.bar(names, values)A bar chart; plt.barh lies sideways.plt.hist(values, bins=10)A histogram: how many values fall into each range?plt.pie(values, labels=names)A pie chart, autopct="%1.0f%%" shows percentages.Labels and showing
plt.title("Title")Heading.plt.xlabel("x")Label of the x axis, plt.ylabel of the y axis.plt.legend()A legend from the label= arguments.plt.grid(True)Grid lines.plt.show()Shows the chart.plt.savefig("chart.png")Saves the chart as a file to download.fig, ax = plt.subplots()For several charts side by side: plt.subplots(1, 2).Example: Draw a parabola
Open in the editor ↗import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 50)
plt.plot(x, x ** 2, label="x²")
plt.plot(x, 2 * x + 1, "r--", label="2x + 1")
plt.title("Two functions")
plt.legend()
plt.grid(True)
plt.show()
Example: Bars: favorite subjects
Open in the editor ↗import matplotlib.pyplot as plt
subjects = ["Math", "Sports", "Art", "CS"]
votes = [5, 9, 4, 8]
plt.bar(subjects, votes, color="seagreen")
plt.title("Favorite subject of class 7b")
plt.ylabel("Votes")
plt.show()
Data from the internet (requests) #
With requests your program fetches data from a server, often in the JSON format. The program waits until the answer has arrived.
Requests
r = requests.get(address)Fetches the page or the data at the address. params={"q": "value"} adds parameters.r.status_code200 means: all good. 404: does not exist.r.json()Turns a JSON answer into lists and dictionaries.r.textThe answer as text.requests.post(address, json=data)Sends data to a server.- CORS: in the browser a web page may only read answers from servers that explicitly allow it. Many open data sources (weather, the Wikipedia API, the GitHub API) do, ordinary web pages mostly do not. Then the program reports a
ConnectionErrorwith a hint about CORS – that is not your program’s fault. Use another source or run the program on your own computer.
Example: Weather in London
Open in the editor ↗import requests
r = requests.get("https://api.open-meteo.com/v1/forecast",
params={"latitude": 51.51, "longitude": -0.13, "current": "temperature_2m"})
data = r.json()
print("Now in London:", data["current"]["temperature_2m"], "°C")
Files and projects #
Programs can write and read text files. In the simple mode they only exist while the program runs. In the expert mode they end up in the project and stay saved.
Writing and reading
open("file.txt", "w")Opens for writing ("w" replaces, "a" appends, "r" reads). Best with with open(…) as f: – then the file is closed safely.f.write("Text\n")Writes text; \n starts a new line.f.read()Reads the whole file as text.for line in f:Reads line by line; line.strip() removes the line break.os.listdir()Names of the files in the project; os.path.exists("file.txt") checks whether it exists.json.dump(data, f)Saves lists and dictionaries; json.load(f) reads them back.Projects (expert mode)
import helpersGets your own file helpers.py from the project; then helpers.function(). Folders work as packages too (from game import characters).SavingProjects live in the browser and are saved automatically. In Chrome and Edge on a computer you can open a folder; otherwise there is export and import as a ZIP.Simple | ExpertThe switch at the top right takes your code along in both directions.Example: Write and read a file
Open in the editor ↗with open("notes.txt", "w") as f:
f.write("Monday: learned Python\n")
f.write("Tuesday: built a game\n")
with open("notes.txt") as f:
for line in f:
print(line.strip())
Finding bugs (debugger) #
If a program does not do what you expected, go through it line by line and look at the variables. Error messages appear in English, with the line to click on.
Simple mode
Single step (→)The arrow button next to “Run” starts the program paused before the first line. Every further press runs one line.BreakpointClick to the left of the line number: the program stops there. Another click removes it.VariablesWhile paused the page shows every variable with its value, split into global and local (inside functions).Stop (■)Ends the program, even an endless loop – the page never freezes.Expert mode
F5Run, or continue to the next breakpoint; ⇧ F5 starts step by step.F10 (Over)Next line; a function runs in one go.F11 (Into)Into the called function, also into other files of the project.⇧ F11 (Out)Let the current function run to its end.Call stackShows which function called which. Lists and dictionaries in the variables can be opened.Example: Watch it step by step
Open in the editor ↗def double(n):
result = n * 2
return result
total = 0
for i in range(1, 4):
total = total + double(i)
print("Sum:", total)