Skip to content

alphaPlan · Programming in a Data World · Cheat-sheet 01

Getting started

Steer a small on-screen robot with Python, store values in variables, make decisions, and repeat work with loops.

Ideas to remember

  1. 01A Turtle program always has four steps: import the turtle tools, create a turtle, draw with it, then finish with turtle.done().
  2. 02A variable is a named container with a name and a value, and the value can change while the program runs.
  3. 03Python is case sensitive and groups code by indentation, so Score and score are different names and the indent is not decoration.
  4. 04An if runs its indented block only when the condition is true, else covers the other case, and elif tests further cases in order.
  5. 05A while loop repeats while a condition stays true; a for loop runs once for each item in a sequence.
  6. 06A loop inside a loop builds grids: the inner loop runs all the way through for each single step of the outer loop.

Words

skk.forward(100)
Moves the turtle 100 pixels in the direction it is facing.
skk.left(120)
Turns the turtle anticlockwise on the spot by 120 degrees; right(angle) turns it clockwise.
age = age + 1
Read the right side first, work out the answer, then store it back in the container.
random.randint(a, b)
A whole number from a to b, both ends included; random.random() gives a decimal from 0.0 up to 1.0.
for side in range(4):
Repeats the block four times, because range(4) produces the numbers 0, 1, 2, 3.
break, continue
break stops the loop immediately; continue skips the rest of the current round and goes to the next one.

Do this

  • Trace a program by hand before you run it: follow each variable's value step by step and predict what the turtle draws.
  • When an error appears, read the last line first, find the line number it names, then ask which name or value Python could not find.
  • Pick one spelling for each name and stay with it.
  • Use a for loop when you know the items or the count ahead of time, and a while loop when you cannot say how many rounds it will take.
  • Put something inside every while loop that moves it toward stopping.

Watch out

  • A NameError saying name is not defined means the variable was never given a value, so there is no container by that name to read from.
  • If you forget count = count + 1, the condition never turns false and the loop never stops: an infinite loop.
  • Text goes inside quotation marks, otherwise Python reads it as a name or an instruction.

Found something unclear, outdated or improvable? Suggest an improvement