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 changeMAX_ENERGY =100# a constant (CAPITALS) — don't change itcreature_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 >50and is_adult:
print("Can have a baby.")
if creature_energy <20or is_injured:
print("In danger.")
ifnot is_hungry:
print("Happily full.")
Lists
creatures = ["Spike", "Bramble"] # make a listcreatures.append("Pip") # add to the endcreatures.remove("Spike") # remove by valuefirst = creatures.pop(0) # remove by index, hand it backprint(len(creatures)) # how many itemsprint(creatures[0]) # first item (indexes start at 0!)print(creatures[-1]) # last itemcreatures[0] ="Nibbles"# change an itemif"Pip"in creatures: # is it in the list? print("Found Pip")
Dictionaries (key → value)
creature = {"name": "Spike", "energy": 100} # make oneprint(creature["energy"]) # look up by keycreature["energy"] =80# change a valuecreature["colour"] ="green"# add a new keycreature["energy"] -=20# do maths on a valuedel creature["colour"] # remove a pairprint(len(creature)) # how many pairsif"colour"in creature: # is the key there? print(creature["colour"])
print(creature.get("colour", "grey")) # safe look-up with a backupfor key in creature: ...# loop over keysfor value in creature.values(): ...# loop over valuesfor 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 earlycontinue# skip to the next turn
Randomness
import random # once, at the toprandom.choice(["north", "south"]) # pick a random itemrandom.randint(1, 6) # random whole number 1–6 (both ends)random.random() # random decimal 0.0–1.0if random.random() <0.1: # happens about 10% of the time print("Mutation!")
Functions
deffood_energy(number_of_berries): # define it (parameter in brackets)return number_of_berries *10# hand an answer backgained = food_energy(3) # call it, catch the answer (30)
Errors: try / except
try:
count = int("hello") # this might go wrongexceptValueError:
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
classCreature: # 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
defmove(self): # a method (an action) self.energy -= self.speed
defis_alive(self):
return self.energy >0spike = Creature("Spike", 5) # make an objectprint(spike.energy) # read a propertyspike.move() # call a method
pygame skeleton
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
is_running =Truewhile is_running: # the game loopfor 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 secondpygame.quit()