← Reference

Charts and checking: cheat sheet

Data detective · In any playground, open Reference to copy these.

list

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

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

str

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

str(score)

strip and lower

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

command = command.strip().lower()

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.")

a text bar

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

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

def (function)

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

def shape():
    pass

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

zigzag()
zigzag()
zigzag()
What it draws
Defined once, called three times

count with a dictionary

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

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

test with assert

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

assert clean_hours("5") == 5