← Teacher guide

Deeper Python in the console: cheat sheet

Deeper Python in the console · In any playground, open Reference to copy these.

Working with text

ask and reply

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

name = input("What is your name? ")
print("Hello, " + name)
What it draws
Asks for a name, then says hello

if / else

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

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()
What it draws
Red when x > 0, else blue

grow value

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

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
What it draws
The same spiral, grown by an update

strip and lower

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

command = command.strip().lower()

check then convert

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

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.")
What it draws
A checked ticket total

variable

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

size = 50
Example
length = 120
forward(length)
left(90)
forward(length / 2)
What it draws
length = 120, then half of it

print

Show text or a value in the output box.

print("Hello")

input

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

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

join text

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

"Hello, " + name

split

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

words = command.split()

Lists and dictionaries

while loop

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

while True:
    pass
Example
r = 10
while r < 60:
    circle(r)
    r = r + 15
What it draws
A circle each time, while r < 60

break

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

break

dictionary value

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

star["speed"]

join

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

", ".join(bag)

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.

bag.remove("lamp")

menu loop

A menu that keeps showing until a break runs.

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

list

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

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

dictionary

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

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

in

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

if item in bag:
    pass

Errors and the adventure

int

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

int(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.

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

save with json

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

import json

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

a missing file

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

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

try and except

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

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

read a file

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

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

load with json

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

import json

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