← Objects with turtles

Python turtle and objects reference

Turtle commands, and the objects, dictionaries and classes from Objects with turtles.

Print a cheat sheet (the whole course or one unit, with a picture of what each command draws)

Move

forward(100)

Example

forward(100)
forward

Move the turtle forward. The number is how many steps.

What the example draws

id: forward

backward(100)

Example

backward(100)
backward

Move the turtle backward without turning.

What the example draws

id: backward

right(90)

Example

forward(60)
right(90)
forward(60)
right

Turn clockwise by this many degrees.

What the example draws

id: right

left(90)

Example

forward(60)
left(90)
forward(60)
left

Turn anticlockwise by this many degrees.

What the example draws

id: left

goto(0, 0)

Example

goto(80, 60)
goto

Jump to a position. (0, 0) is the centre; x goes right, y goes up.

What the example draws
From the centre to (80, 60)

id: goto

setheading(0)

Example

setheading(90)
forward(60)
setheading

Face a direction. 0 is right, 90 is up, 180 is left.

What the example draws
setheading(90): facing up

id: setheading

home()

Example

forward(80)
left(90)
forward(40)
home()
home

Go back to the centre, facing right.

What the example draws
Back to the centre, facing right

id: home

Pen

penup()

Example

forward(40)
penup()
forward(40)
pendown()
forward(40)
penup

Lift the pen so moving does not draw.

What the example draws
Pen up for the middle part

id: penup

pendown()

Example

forward(40)
penup()
forward(40)
pendown()
forward(40)
pendown

Put the pen down so moving draws again.

What the example draws
Pen down again for the last part

id: pendown

pensize(5)

Example

pensize(1)
forward(50)
pensize(8)
forward(50)
pensize

Set how thick the line is.

What the example draws
pensize(1), then pensize(8)

id: pensize

pencolor("red")

Example

pencolor("red")
forward(100)
pencolor

Set the line colour, using a colour name.

What the example draws

id: pencolor

dot(20)

Example

dot(30)
hideturtle()
dot

Draw a filled dot of this size.

What the example draws

id: dot

write("Hello")

Example

write("Hello", False, "left", ("Arial", 20, "normal"))
hideturtle()
write

Write text at the turtle's position.

What the example draws

id: write

Fill and look

fillcolor("blue")

Example

fillcolor("blue")
begin_fill()
circle(40)
end_fill()
fillcolor

Choose the colour to fill shapes with.

What the example draws

id: fillcolor

begin_fill()

end_fill()

Example

fillcolor("orange")
begin_fill()
for i in range(4):
    forward(60)
    right(90)
end_fill()
begin_fill / end_fill

Everything drawn between these two lines is filled in.

What the example draws

id: begin-fill-end-fill

bgcolor("lightblue")

Example

bgcolor("lightblue")
forward(80)
bgcolor

Set the background colour.

What the example draws

id: bgcolor

hideturtle()

Example

forward(80)
hideturtle()
hideturtle

Hide the turtle so only the drawing shows.

What the example draws
The line stays; the turtle is hidden

id: hideturtle

speed(10)
speed

How fast the turtle moves, from 1 (slow) to 10 (fast).

id: speed

clear()
clear

Wipe the drawing.

id: clear

Shapes

circle(50)

Example

circle(50)
circle

Draw a circle with this radius.

What the example draws
circle(50) starts at the turtle and curves left

id: circle

for i in range(4):
    forward(100)
    right(90)

Example

for i in range(4):
    forward(100)
    right(90)
square (loop)

Draw a square by repeating forward and right four times.

What the example draws

id: square-loop

Code structure

for i in range(4):
    pass

Example

for i in range(5):
    forward(15)
    penup()
    forward(10)
    pendown()
for loop

Repeat the indented lines this many times.

What the example draws
range(5): five dashes

id: for-loop

while True:
    pass

Example

r = 10
while r < 60:
    circle(r)
    r = r + 15
while loop

Repeat the indented lines for as long as the condition is true.

What the example draws
A circle each time, while r < 60

id: while-loop

name = input("What is your name? ")
print("Hello, " + name)

Example

name = input("What is your name? ")
print("Hello, " + name)
ask and reply

Ask a question, store the typed answer, and use it in a reply.

What the example draws
Asks for a name, then says hello

id: ask-and-reply

text = input("How many? ")
if text.isdigit():
    number = int(text)
    pass
else:
    print("Please type a number.")

Example

text = input("How many tickets? ")
if text.isdigit():
    print("That will be $" + str(int(text) * 12) + ".")
else:
    print("Please type a number.")
check then convert

Check typed text with isdigit before turning it into a number.

What the example draws
A checked ticket total

id: check-then-convert

total = 0
while total < 10:
    total += int(input("Add: "))

Example

total = 0
while total < 10:
    total += int(input("Add: "))
    print("Total: " + str(total))
print("Done")
running total

Start the total at 0 once, then add to it on every pass.

id: running-total

while True:
    choice = input("1 add, 2 quit: ")
    if choice == "1":
        pass
    elif choice == "2":
        break
    else:
        print("Please choose 1 or 2.")

Example

total = 0
while True:
    choice = input("1 add $5, 2 pay: ")
    if choice == "1":
        total += 5
    elif choice == "2":
        break
    else:
        print("Please choose 1 or 2.")
print("Pay $" + str(total))
menu loop

A menu that keeps showing until a break runs.

id: menu-loop

if x > 0:
    pass
else:
    pass

Example

for x in [-90, -30, 30, 90]:
    penup()
    goto(x, 0)
    if x > 0:
        dot(30, "red")
    else:
        dot(30, "blue")
hideturtle()
if / else

Do one thing or the other, depending on a condition.

What the example draws
Red when x > 0, else blue

id: if-else

for i in range(8):
    if i % 2 == 0:
        pass
    else:
        pass

Example

for i in range(8):
    if i % 2 == 0:
        pencolor("red")
    else:
        pencolor("blue")
    pensize(6)
    forward(30)
    right(45)
every other

i % 2 == 0 is true on every second pass.

What the example draws
Red and blue sides, taking turns

id: every-other

size = 50

Example

length = 120
forward(length)
left(90)
forward(length / 2)
variable

Give a value a name, so you can reuse and change it.

What the example draws
length = 120, then half of it

id: variable

sides = 5
for i in range(sides):
    forward(60)
    right(360 / sides)

Example

sides = 6
for i in range(sides):
    forward(60)
    right(360 / sides)
named turn

Name the number of sides once; the turn is worked out from it.

What the example draws
A hexagon: change sides and the turn follows

id: named-turn

for i in range(20):
    forward(i * 5)
    right(90)

Example

for i in range(30):
    forward(i * 5)
    right(90)
counter step

Use the counter i to make each pass different.

What the example draws
A square spiral: each line longer than the last

id: counter-step

size = 5
for i in range(20):
    forward(size)
    right(90)
    size = size + 5

Example

size = 5
for i in range(30):
    forward(size)
    right(90)
    size = size + 5
grow value

Change a value every pass: read the old one, store a new one.

What the example draws
The same spiral, grown by an update

id: grow-value

colours = ["red", "blue", "green"]
list

Keep many values in order under one name. The first item is place 0.

id: list

for c in colours:
    pass

Example

pensize(6)
for c in ["red", "blue", "green"]:
    pencolor(c)
    forward(40)
for each item

Work through a list, one item at a time.

What the example draws
One line per colour in the list

id: for-each-item

def shape():
    pass

shape()

Example

def zigzag():
    left(45)
    forward(30)
    right(90)
    forward(30)
    left(45)

zigzag()
zigzag()
zigzag()
def (function)

Name a group of steps, then run it by calling its name.

What the example draws
Defined once, called three times

id: def-function

print("Hello")
print

Show text or a value in the output box.

id: print

import random

n = random.randint(1, 10)
random number

Pick a random whole number between two values.

id: random-number

Events and input

def stamp(x, y):
    goto(x, y)
    dot(20)

onscreenclick(stamp)
listen()
mainloop()

Example

def stamp(x, y):
    goto(x, y)
    dot(20)

penup()
stamp(-60, 30)
stamp(50, -20)
hideturtle()
onscreenclick

Run a function every time the picture is clicked. It receives the click position.

What the example draws
After two clicks

id: onscreenclick

def go_up():
    forward(20)

onkey(go_up, "Up")
listen()
mainloop()

Example

def go_up():
    forward(20)

go_up()
go_up()
go_up()
onkey

Run a function every time a key is pressed. Click the picture first so it receives keys.

What the example draws
After pressing Up three times

id: onkey

def tick():
    forward(5)
    ontimer(tick, 50)

tick()
mainloop()
ontimer

Run a function again after a number of milliseconds. A function can start its own timer.

id: ontimer

n = numinput("Title", "How many?")
numinput

Ask for a number in a pop-up. The answer is None if the pop-up is cancelled.

id: numinput

name = textinput("Title", "Your name?")
textinput

Ask for text in a pop-up.

id: textinput

Text in and out

name = input("What is your name? ")
input

Show a question in the console, wait for an answer, and store what was typed. It is always text.

id: input

"Hello, " + name
join text

Join pieces of text into one with +. Spaces only appear where they are inside the quotes.

id: join-text

str(score)
str

Turn a number into text, so it can be joined: "Score: " + str(score).

id: str

int(text)
int

Turn text made of digits, such as "12", into a whole number you can calculate with.

id: int

text.isdigit()
isdigit

True if the text is all digits (0 to 9) and not empty, so int() will work on it.

id: isdigit

total += 1
add to (+=)

Add to a variable: total += 5 is short for total = total + 5.

id: add-to

break
break

Leave the loop straight away; the program carries on after it.

id: break

Objects

star = Turtle()
star.shape("circle")
star.forward(50)
new turtle

Make another turtle with its own name. Put the name and a dot in front of a command to give it to that turtle.

id: new-turtle

star = {"speed": 5, "points": 1}
dictionary

Values stored under names (keys). One dictionary can hold everything about one thing.

id: dictionary

star["speed"]
dictionary value

The value stored under that key. The key goes in quotes. Assign to it to change it: star["speed"] = 8.

id: dictionary-value

class Star:
    def __init__(self, x):
        self.speed = 5

s = Star(100)
class

A new kind of object. __init__ runs when one is made; self.name = value stores a value in that object.

id: class

    def move(self):
        self.turtle.forward(self.speed)
method

A function inside a class. Call it on one object: star.move(). self is that object.

id: method

Text and collections

command = command.strip().lower()
strip and lower

strip() removes spaces at the ends; lower() and upper() change the capitals. Each gives back new text.

id: strip-and-lower

words = command.split()
split

Cut text into a list of words at the spaces: "go north".split() is ["go", "north"].

id: split

if item in bag:
    pass
in

True if the item is in the list (or the key is in the dictionary, or the letters are in the text).

id: in

", ".join(bag)
join

Join a list of texts into one, with the text in quotes between each: "lamp, key".

id: join

bag.remove("lamp")
remove from a list

Take an item out of a list. It stops with a ValueError if the item is not there, so check with in first.

id: remove-from-a-list

items.sort()
sort

Put a list in order (A to Z, or smallest first). It changes the list itself.

id: sort

try:
    n = int(text)
except ValueError:
    print("That is not a number.")
try and except

Run lines that might fail. If the named error happens, the except lines run instead of the program stopping.

id: try-and-except

Files

with open("save.txt", "w") as f:
    f.write(text)
write a file

"w" makes the file, or empties it first if it is already there, then writes. with closes the file at the end.

id: write-a-file

with open("save.txt") as f:
    text = f.read()
read a file

Opens the file to read and gives you all of it as one piece of text.

id: read-a-file

import json

with open("game.json", "w") as f:
    json.dump(game, f)
save with json

Writes a dictionary or list to a file as JSON text.

id: save-with-json

import json

with open("game.json") as f:
    game = json.load(f)
load with json

Reads JSON text back into the dictionary or list that was saved.

id: load-with-json

try:
    with open("save.txt") as f:
        text = f.read()
except FileNotFoundError:
    print("There is no save yet.")
a missing file

The first time, there is no file: catch FileNotFoundError instead of stopping.

id: a-missing-file

Data

import csv

with open("music.csv") as f:
    rows = list(csv.DictReader(f))
read a CSV

Each row of the file becomes a dictionary, keyed by the column names in the first line. Every value is text.

id: read-a-csv

counts = {}
for row in rows:
    key = row["genre"]
    if key in counts:
        counts[key] = counts[key] + 1
    else:
        counts[key] = 1
count with a dictionary

One count for each different value: add 1 if the key is there already, or start it at 1.

id: count-with-a-dictionary

print(label.ljust(12) + "#" * n)
a text bar

"#" * 5 is #####. ljust pads the label to the same width, so the bars line up.

id: a-text-bar

assert clean_hours("5") == 5
test with assert

A test case: nothing happens if it is true; the program stops with AssertionError if it is not.

id: test-with-assert

import pandas as pd

songs = pd.read_csv("music.csv")
read a CSV with pandas

Reads the whole file into a table (a DataFrame). Numbers stay numbers.

id: read-a-csv-with-pandas

rows = songs[songs["genre"] == genre]
filter a table

Keeps the rows where the test is true, as a smaller table.

id: filter-a-table

import gradio as gr

def answer(choice):
    return "You chose " + choice

gr.Interface(fn=answer, inputs=gr.Dropdown(["pop", "rock"]), outputs="text").launch()
an app with Gradio

Gradio calls your function with what was chosen, and shows what it returns.

id: an-app-with-gradio

{"q": "What is 7 x 8?", "choices": ["54", "56", "64"], "answer": "56"}

inputs.append(gr.Radio(q["choices"], label=q["q"]))
a quiz question

A question as a dictionary, and a Radio input made from it: the student picks one of the choices, and the function gets that text.

id: a-quiz-question

import requests

try:
    reply = requests.get("https://api.open-meteo.com/v1/forecast", params={"latitude": -35.28, "longitude": 149.13, "daily": "temperature_2m_max"}, timeout=10).json()
except requests.RequestException:
    print("No connection")
ask an API

Asks an API at that address (params become the ?query string) and turns the JSON reply into dictionaries and lists. Plan for no connection.

id: ask-an-api

Web apps

@app.route("/about")
def about():
    return "<h1>About</h1>"
a Flask route

Joins an address to a function. What the function returns is the page.

id: a-flask-route

PAGE = """<ul>
{% for m in members %}
  <li>{{ m["name"] }}</li>
{% endfor %}
</ul>"""

return render_template_string(PAGE, members=members)
a page from a template

A template is HTML with gaps: {{ }} shows a value, {% for %} repeats a part for each item.

id: a-page-from-a-template

@app.route("/group/<name>")
def group(name):
    return "You asked for  + name
an address with a part that changes

<name> matches any word in that place of the address, and is passed to the function.

id: an-address-with-a-part-that-changes

@app.route("/join", methods=["POST"])
def join():
    name = request.form["name"].strip()
read a form

A form with method='post' sends each box that has a name='...' attribute. request.form looks them up by that name.

id: read-a-form

return redirect("/")
go to another page

Sends the browser on to another address, such as back home after a form.

id: go-to-another-page

with open("members.csv", "a", newline="") as f:
    csv.writer(f).writerow([name, group])
add a row to a CSV

"a" adds to the end of the file instead of emptying it. Each list becomes one row.

id: add-a-row-to-a-csv

@app.route("/api/members")
def api_members():
    return {"members": members}
send JSON

Return a dictionary and Flask sends it as JSON, for other programs to read.

id: send-json

@api.get("/year")
def year(y: int):
    return {"next": y + 1}
a FastAPI route

The type after each parameter (int, str, float) is checked: a wrong value gets an error reply (422) before your code runs.

id: a-fastapi-route

Machine learning

random.seed(1)
random.shuffle(penguins)
train = penguins[:250]
test = penguins[250:]
test a model

Shuffle, then keep some examples back. Train on one part; test only on the other.

id: test-a-model

from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)
model = KNeighborsClassifier(n_neighbors=1)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
train and score a model

fit learns from the training examples; score tests on the held-back ones (1.0 is 100%).

id: train-and-score-a-model

mystery = pd.DataFrame([[47.0, 215.0]], columns=X.columns)
print(model.predict(mystery)[0])
predict with a model

The new example needs the same columns, in the same order, as the training data.

id: predict-with-a-model