🐍 Python Reference

Every function and idea from Worksheets 1 to 7, in one place.

A quick cheat-sheet for everything you've learned so far.

Want to try something out? Open the Python Scratchpad and paste it in.

Output

print("Hello!")
print(7 * 6)

Show a message or a number on the screen.

Worksheet 1
print("Score:", score)
print(name, "is", age)

List several things separated by commas. Python puts a space between them.

Worksheet 5

Input

age = get_input()

Read whatever was typed into the input box.

Worksheet 2
first = get_input('first_number')
second = get_input('second_number')

When there's more than one box, read each one by its name.

Worksheet 2
choice = get_choice(2)
if choice == 1:
  print("First button")

Show buttons and get back which one was pressed (1, 2, ...).

Worksheet 4

Variables & types

side = 5
area = side * side
print(area)     # 25

Store a value in a name, then reuse it as many times as you like, even to work out new values.

Worksheet 2
score = 0      # whole number
price = 2.5    # decimal

Numbers can be whole (int) or decimals (float).

Worksheet 1
greeting = "hello"
letter = 'a'

Text goes in quotes. Use matching quotes, both " or both '.

Worksheet 5
found = True
done = False

A boolean is either True or False (capital letters).

Worksheet 4
scores = [7, 3, 9]

A list holds several items in order, inside square brackets.

Worksheet 6

Maths

2 + 3      # add
10 - 4     # subtract
6 * 7      # multiply
20 / 4     # divide

The four basic operators.

Worksheet 1
2 + 3 * 4      # 14, not 20
(2 + 3) * 4    # 20

* and / happen before + and -. Use ( ) to change the order.

Worksheet 1
13 % 5        # 3 (the remainder)
n % 2 == 0    # True when n is even

% gives the remainder after dividing. Great for even/odd checks.

Worksheet 5

Comparing & booleans

a > b     # greater than
a < b     # less than
a == b    # equal to
a != b    # not equal to
a >= b    # greater or equal
a <= b    # less or equal

Each comparison gives back True or False.

Worksheet 4
if x > 0 and x < 10:
  print("in range")

if day == "Sat" or day == "Sun":
  print("weekend!")

if not done:
  print("keep going")

Join tests together to make richer decisions: and needs both true, or needs either true, not flips it.

Worksheet 4

Decisions (if)

if score > 10:
  print("Great!")
elif score > 5:
  print("Good")
else:
  print("Keep going")

Run different code depending on what's true. Indent each body 2 spaces. elif and else are optional.

Worksheet 4
a = 5
a = a + 7      # now a is 12
if a > 10:
  a = 10       # too big! set it back to 10
print(a)       # 10

Keep a value inside a limit: after changing it, check whether it went too far, and if so set it back to the limit. Programmers call this clamping.

Worksheet 4

Loops

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

range(5) counts from 0 up to 4. The indented lines run each time.

Worksheet 3
for n in range(1, 6):
  print(n)     # 1 2 3 4 5

Count from a start up to (but not including) the stop number.

Worksheet 3
for colour in ["red", "blue"]:
  print(colour)

Do something with each item of a list in turn.

Worksheet 3
for n in range(100):
  if n == 7:
    break

break leaves the loop straight away.

Worksheet 5
for y in range(3):
  for x in range(3):
    print(x, y)

A loop inside a loop. The inner body is indented twice (4 spaces).

Worksheet 3

Text (strings)

"hello" + " " + "world"
# "hello world"

+ joins strings together.

Worksheet 5
"*" * 5      # "*****"

* repeats a string.

Worksheet 3
len("hello")    # 5

len() counts the characters in a string.

Worksheet 5

Lists

nums = [10, 20, 30]
nums[0]     # 10  (the first item)
nums[2]     # 30

Read an item by its position. Counting starts at 0.

Worksheet 6
nums[1] = 99

Replace the item at a position with a new value.

Worksheet 6
len(nums)     # 3

len() counts how many items are in the list.

Worksheet 6
nums.append(40)

.append() adds an item to the end.

Worksheet 6
for i in range(len(nums)):
  print(i, nums[i])

Loop with the index when you need the position as well as the item.

Worksheet 6

Functions

def greet():
  print("Hi!")

greet()

def makes a reusable block of code. Run it by writing its name with ().

Worksheet 7
def add(a, b):
  print(a + b)

add(2, 3)     # 5

Pass values in through the brackets. They become a and b inside.

Worksheet 7
def double(n):
  return n * 2

answer = double(5)    # 10

return hands a result back so you can store or use it. (print only shows it.)

Worksheet 7

Handy patterns

total = 0
for n in [3, 5, 2]:
  total = total + n
print(total)     # 10

Running total: start at 0, add each time through the loop, use it after.

Worksheet 3
count = 0
for n in nums:
  if n > 10:
    count = count + 1

Counter: count how many items match a test.

Worksheet 6
evens = []
for n in range(10):
  if n % 2 == 0:
    evens.append(n)

Build a list: start empty, append the items you want to keep.

Worksheet 6
found = False
for n in nums:
  if n == target:
    found = True

Flag: remember whether something happened while looping.

Worksheet 5
biggest = nums[0]
for n in nums:
  if n > biggest:
    biggest = n

Biggest / smallest: start with the first item, update when you see a better one.

Worksheet 6