11. Cheat Sheet

A quick reminder of all the important bits. When you nearly remember how to do something, look here first.


Printing & comments

print("Hello!")            # show something on screen
# this is a comment — the computer ignores it

Variables & constants

creature_energy = 100      # a variable (snake_case) — can change
MAX_ENERGY = 100           # a constant (CAPITALS) — don't change it
creature_energy -= 20      # take 20 away (also += and *=)

f-strings (values inside text)

name = "Spike"
print(f"{name} has {creature_energy} energy.")

Asking a question

answer = input("How many? ")
count = int(answer)        # turn text into a whole number

Comparing things

==   # is equal to        !=   # is NOT equal to
>    # greater than       <    # less than
>=   # greater or equal   <=   # less or equal

if / elif / else

if creature_energy > 80:
    print("Full of energy!")
elif creature_energy > 0:
    print("Getting tired.")
else:
    print("Out of energy.")

Combining tests

if creature_energy > 50 and is_adult:
    print("Can have a baby.")
if creature_energy < 20 or is_injured:
    print("In danger.")
if not is_hungry:
    print("Happily full.")

Lists

creatures = ["Spike", "Bramble"]   # make a list
creatures.append("Pip")            # add to the end
creatures.remove("Spike")          # remove by value
first = creatures.pop(0)           # remove by index, hand it back
print(len(creatures))              # how many items
print(creatures[0])                # first item (indexes start at 0!)
print(creatures[-1])               # last item
creatures[0] = "Nibbles"           # change an item
if "Pip" in creatures:             # is it in the list?
    print("Found Pip")

Dictionaries (key → value)

creature = {"name": "Spike", "energy": 100}   # make one
print(creature["energy"])                     # look up by key
creature["energy"] = 80                        # change a value
creature["colour"] = "green"                   # add a new key
creature["energy"] -= 20                        # do maths on a value
del creature["colour"]                          # remove a pair
print(len(creature))                            # how many pairs

if "colour" in creature:                        # is the key there?
    print(creature["colour"])
print(creature.get("colour", "grey"))           # safe look-up with a backup

for key in creature: ...                        # loop over keys
for value in creature.values(): ...             # loop over values
for key, value in creature.items(): ...         # loop over both

Use a list for many things in order; a dictionary for named values you look up.


Loops

for creature in creatures:         # once per item
    print(creature)

for step in range(5):              # 0, 1, 2, 3, 4
    print(step)

while creature_energy > 0:         # keep going while true
    creature_energy -= 10          # (change something, or it loops forever!)

break        # jump out of a loop early
continue     # skip to the next turn

Randomness

import random                          # once, at the top

random.choice(["north", "south"])      # pick a random item
random.randint(1, 6)                   # random whole number 1–6 (both ends)
random.random()                        # random decimal 0.0–1.0
if random.random() < 0.1:              # happens about 10% of the time
    print("Mutation!")

Functions

def food_energy(number_of_berries):    # define it (parameter in brackets)
    return number_of_berries * 10      # hand an answer back

gained = food_energy(3)                # call it, catch the answer (30)

Errors: try / except

try:
    count = int("hello")               # this might go wrong
except ValueError:
    print("That wasn't a number.")     # runs if it does
    count = 1

Read errors from the bottom line up. Common ones: NameError, TypeError, ValueError, IndexError, IndentationError.


Classes & objects

class Creature:                        # blueprint (Capital name)
    def __init__(self, name, speed):   # setup — runs when you make one
        self.name = name               # a property (self = this creature)
        self.energy = 100
        self.speed = speed

    def move(self):                    # a method (an action)
        self.energy -= self.speed

    def is_alive(self):
        return self.energy > 0

spike = Creature("Spike", 5)           # make an object
print(spike.energy)                    # read a property
spike.move()                           # call a method

pygame skeleton

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

is_running = True
while is_running:                              # the game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False

    screen.fill((30, 30, 40))                  # clear the background
    pygame.draw.circle(screen, (0, 200, 0), (400, 300), 20)   # draw
    pygame.display.flip()                      # show it
    clock.tick(60)                             # 60 frames per second

pygame.quit()
  • Colours are (red, green, blue), each 0–255.
  • Positions are (x, y)y gets bigger going down.
  • pygame.draw.circle(screen, colour, (x, y), radius)
  • pygame.draw.rect(screen, colour, (x, y, width, height))

The naming rules (so your code looks right)

ThingStyleExample
Variablelowercase snake_casecreature_energy
ConstantUPPERCASEMAX_ENERGY
Function / methodsnake_casedef move(self):
ClassCapitalised (PascalCase)class Creature:

The three rules to remember when stuck

  1. Read the error’s bottom line — it names the problem and the line.
  2. Check your indents — code inside if, for, while, def and class must be pushed in 4 spaces.
  3. Type it, run it, break it, fix it. Every programmer learns this way. 🚀