Year 8 · Python I · Part C: Telling it what to do

Programming basics

In one line

A program stores information in variables, works on it with operators, and controls the order with sequence, selection and iteration. Examples are in Python, with Scratch alongside for Year 7.

1

Read a Scratch script and write the same thing in Python.

2

Use variables, the four data types and casting, and spot the input() bug.

3

Work out DIV (//) and MOD (%) by hand, and use MOD to test for even numbers.

4

Trace if / elif / else, for with range() and while loops line by line.

5

Tell syntax, runtime and logic errors apart, and fix each kind.

VariableA named box in memory that holds one value.
AssignmentPutting a value in a variable: score = 0.
CastingChanging a value's type: int("13").
ConcatenationJoining strings: "7" + "7" = "77".
SelectionChoosing a path with if / elif / else.
IterationRepeating: a for or while loop.
BooleanA value that is only True or False.
Infinite loopA loop that never stops.

From Scratch to Python

Scratch and Python do the same jobs. In Scratch you snap blocks. In Python you type the words. The ideas are identical; only the spelling changes.

SCRATCHPYTHON when ⚑ clicked set score to 0 ask Name? and wait repeat 3 change score by 10 say score # you press Run score = 0 name = input("Name? ") for i in range(3): score = score + 10 print(score) 4 spaces of indent = "inside the loop"
Block colours follow Scratch: yellow = events and control, orange = variables, teal = sensing, purple = looks. The Scratch C-block "hugs" the blocks it repeats. Python shows the same thing with 4 spaces of indent.
ScratchPythonWhat it does
say [Hello]print("Hello")Show something on screen
ask [Name?] and waitname = input("Name? ")Get typed input
set [score] to 0score = 0Assignment
change [score] by 1score = score + 1Update a variable
if … then … elseif …: / else:Selection
repeat 10for i in range(10):Count-controlled loop
repeat until …while not …:Condition-controlled loop
foreverwhile True:Loop for ever
pick random 1 to 10random.randint(1, 10)Random whole number (needs import random)

Sequence: top to bottom

print("Hello")
print("Welcome to Computing")
Hello Welcome to Computing

Line 1 runs, then line 2. That's sequence. print() shows what's inside the brackets. Every program uses sequence, selection and iteration: you'll meet all three on this page.

?Why?

Why move from blocks to typing? Blocks can't have spelling mistakes, which is great for learning ideas. But typed code is faster to write, easy to copy and search, and it's what real programmers use. Year 8 also uses MIT App Inventor, which is blocks again: the same ideas, built into a phone app.

The exam boards write it differently again

IdeaPythonAQA 8525 pseudocodeOCR J277 reference language
Assignmentscore = 0score ← 0score = 0
Outputprint(score)OUTPUT scoreprint(score)
Inputname = input()name ← USERINPUTname = input()
Count loopfor i in range(1, 11):FOR i ← 1 TO 10 … ENDFORfor i = 1 to 10 … next i
DIV / MOD7 // 2 · 7 % 27 DIV 2 · 7 MOD 27 DIV 2 · 7 MOD 2
!Watch out

Exam loops include the last number: FOR i ← 1 TO 10 runs 10 times, ending on 10. Python's range(1, 10) stops before 10. Step 7 shows why.

Variables: labelled boxes

A variable is a named box in memory that holds one value. The name stays the same. The value inside can change while the program runs.

score = 0 score 0 Make a box called score.Put 0 in it. score = score + 10 right side first: 0 + 10 = 10 score 010 1 read 2 write The old 0 is thrown away. best = score score10 best10 copy
Python always works out the right side first, then puts the answer in the box named on the left. A box holds one value at a time.
  1. score = 0: make a box called score, put 0 in it. This is assignment.

  2. score = score + 10: read the right side first. 0 + 10 = 10. Put 10 back in the box.

  3. print(score) shows 10. No quotes: it shows what's in the box, not the word "score".

!Watch out

In code, = means store, not "equals". score = score + 10 is nonsense in maths but perfect in code. To ask whether two things are equal, use ==. Read = aloud as "becomes": "score becomes score plus 10".

★Naming rules

Letters, digits and _ only. Can't start with a digit. No spaces. Case matters: Score and score are two different boxes. Use clear names: lives, not x. Python style is snake_case: high_score.

e.g.In Scratch

The orange set score to 0 and change score by 10 blocks. The little box on the stage that shows the score is a window into the variable.

Data types and casting

Every value has a type. The type decides what you can do with it. 7 + 7 adds. "7" + "7" joins.

TypeHoldsPython examplesIn memory (Topics 3–4)
Integer (int)Whole numbers7, -3, 0Binary number (two's complement for negatives)
Float (float)Decimal numbers3.14, 0.5, 7.0A number and a "where the point goes" part
String (str)Text, in quotes"Hello", "7", ""One character code after another (Unicode)
Boolean (bool)True or FalseTrue, FalseCould be 1 bit; Python uses more
▶

Type guesser

What type is this value? Tap one. The quotes, the dot and the capital letter are your clues.

0 of 0 right

Input and casting

name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hi " + name + ", next year you'll be " + str(age + 1))
  1. input() always gives back a string, even if you type digits. Type 13 and you get "13".

  2. int() turns "13" into 13 so you can do maths. Changing type is casting. float("2.5") and str(14) are casting too.

  3. str() turns 14 back into text so it can be joined to other text with +.

The classic bug
age = input("Age? ")   # you type 13
print(age + 1)
TypeError: can only concatenate str (not "int") to str
Fixed with casting
age = int(input("Age? "))   # 13
print(age + 1)
14
!Watch out

"7" + "7" gives "77" (joining text, called concatenation). 7 + 7 gives 14. And int("seven") crashes: casting only works when the text looks like a number.

?Why?

Why doesn't Python guess? "007" might be a James Bond code, not the number 7. A phone number should stay as text. Python makes you say what you mean. (Topic 4: the character '7' is code 55, not 7.)

Arithmetic: +, −, ×, ÷, DIV and MOD

Python does maths with operators. Most are like a calculator. Two are new and very useful: // (DIV) and % (MOD).

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide (always gives a float)7 / 2 · 6 / 23.5 · 3.0
//Whole-number divide (DIV)7 // 23
%Remainder (MOD)7 % 21
**Power2 ** 8256
▶

Share the sweets: DIV and MOD

Share a sweets between b friends. Everyone gets the same whole number. Each row is one round of handing out.

By hand: 17 DIV 5 and 17 MOD 5

  1. How many 5s fit into 17? Count up in 5s: 5, 10, 15. The next one, 20, is too big.

  2. Three 5s fit. So 17 // 5 = 3. That's DIV.

  3. Three 5s make 15. What's left? 17 − 15 = 2. So 17 % 5 = 2. That's MOD.

  4. Check: 3 × 5 + 2 = 15 + 2 = 17 ✓. The remainder (2) is always smaller than what you divide by (5).

The even/odd test

n = int(input("Number: "))
if n % 2 == 0:
    print("even")
else:
    print("odd")
nn // 2n % 2Even?
630Yes
731No
1050Yes
1361No

Even numbers split into 2 with nothing left, so n % 2 is 0. Odd numbers always leave 1.

e.g.MOD in real programs

Minutes and seconds: 200 seconds → 200 // 60 = 3 minutes, 200 % 60 = 20 seconds. Last digit of a number: 1234 % 10 = 4. Every 3rd turn: if turn % 3 == 0:. Clocks: 15:00 + 11 hours → (15 + 11) % 24 = 2 o'clock.

!Watch out

Order of operations is the same as maths (BIDMAS): 2 + 3 * 4 is 14, not 20. Use brackets to be sure: (2 + 3) * 4 = 20.

Comparisons and Boolean operators

A comparison asks a question. The answer is always True or False: a Boolean. Every if and every while runs on one.

OperatorMeaningExampleAnswer
==Equal to5 == 3False
!=Not equal to5 != 3True
> <Greater than / less than5 > 3True
>= <=Greater / less than or equal5 <= 3False

Join questions with and, or, not. These are the logic gates from Topic 9.

ABA and BA or Bnot A
FalseFalseFalseFalseTrue
FalseTrueFalseTrueTrue
TrueFalseFalseTrueFalse
TrueTrueTrueTrueFalse
  1. The code: age = 13, then if age >= 11 and age <= 14:

  2. Swap in the value: 13 >= 11 and 13 <= 14.

  3. Work out each side: True and True.

  4. and needs both sides True. They are, so the answer is True: age 13 is in KS3.

!Watch out

if age == 12 or 13: is always True. Python reads it as (age == 12) or (13), and 13 counts as True. Write the comparison twice: age == 12 or age == 13.

★Remember

True and False start with a capital letter in Python. No quotes: "True" with quotes is a string.

Selection: if, elif, else

Selection lets the program choose a path. Python checks each condition from the top. The first True one wins, and the rest are skipped.

score = int(input("Score out of 50: "))
if score >= 40:
    print("Gold badge!")
elif score >= 25:
    print("Bronze badge")
else:
    print("Try the Respawn quest")
Start score >= 40? True Gold badge! False score >= 25? True Bronze badge False (else) Try the Respawn quest End Only ONE of the three green boxes ever runs.
  1. Check the if. True? Run its indented lines and skip the rest.

  2. False? Check the elif ("else if"). You can have as many elifs as you like.

  3. Nothing true? Run the else. It has no condition: it catches everything left.

scorescore >= 40?score >= 25?Output
45Truenot checkedGold badge!
40Truenot checkedGold badge!
30FalseTrueBronze badge
12FalseFalseTry the Respawn quest
!Watch out

Order matters. If >= 25 came first, a score of 45 would wrongly get Bronze, because 45 >= 25 is True and Python would stop there. Put the strictest test first.

★Remember

Indentation (4 spaces) shows which lines are inside the if. The colon : at the end of the if line is required. Thonny and IDLE indent for you after a colon.

e.g.Test data

Test the boundaries: 40 and 39, 25 and 24. Most selection bugs hide at the edges (> vs >=).

Iteration with for and range()

A for loop repeats a set number of times. It's a count-controlled loop: Scratch's "repeat 5". range() makes the list of numbers to count through.

for i in range(5):
    print("Lap", i)
Lap 0 Lap 1 Lap 2 Lap 3 Lap 4

range(5) gives 0, 1, 2, 3, 4: it starts at 0 and stops before 5. Five numbers, so five laps. Each lap, i takes the next number.

range(start, stop, step). Start is included. Each hop adds step. Stop is a fence: you never land on it or go past it.
CodeNumbersTimes it runs
range(5)0, 1, 2, 3, 45
range(1, 6)1, 2, 3, 4, 55
range(2, 10, 3)2, 5, 83
range(10, 0, -2)10, 8, 6, 4, 25
range(5, 5)(nothing)0
▶

range() visualiser

?Why?

Why does range stop before the end? So range(n) gives exactly n numbers, and so it matches list positions, which also start at 0 (Topic 14). range(len(names)) visits every position, no more, no less.

★Count the laps

With step 1: laps = stop − start. range(3, 10) runs 10 − 3 = 7 times. With a bigger step, list the numbers and count them.

while loops, and loops that never stop

A while loop repeats as long as a condition is True. It's a condition-controlled loop. Use it when you don't know how many laps you'll need.

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Lift off!")
3 2 1 Lift off!
count = 3 count > 0? False print("Lift off!") True print(count) count = count - 1 loop backand check again Laps: count = 3 → 2 → 1 → 0. When count is 0, 0 > 0 is False, so the loop ends.
The condition is checked before every lap. The indented lines (orange) are the loop body. Something in the body must change the condition, or it never ends.

A loop that waits for the right answer

password = ""
while password != "dragon":
    password = input("Password: ")
print("Access granted")

Repeats while the condition is True. As soon as the user types dragon, password != "dragon" is False and the loop ends. It might run once, or a hundred times.

!Infinite loops

If the condition can never become False, it loops for ever: an infinite loop. Delete count = count - 1 above and count stays 3, so 3 > 0 is True for ever. To stop it in Thonny, press Stop or Ctrl + C.

forwhile
Type of loopCount-controlledCondition-controlled
Use whenYou know how many timesYou repeat until something happens
Scratchrepeat 10repeat until … (Python: while not …) · forever (while True)
Can it be infinite?No (range always ends)Yes, if the condition never becomes False
e.g.Infinite on purpose

Games and the traffic light build (Step 11) use while True: on purpose: the main loop should run until the power goes off. An Arduino's loop() is the same idea.

String basics

A string is a row of characters. Each character has a numbered position called an index. The first index is 0.

word[0] is the first character. word[-1] counts from the end. A slice word[0:3] stops before 3, just like range.
Code (word = "Python")ResultWhat it does
len(word)6How many characters
word[0]"P"Character at index 0
word[-1]"n"Last character
word[0:3]"Pyt"Slice: index 0 up to (not including) 3
word.upper()"PYTHON"All capitals (Topic 4: the 32s bit switched off)
word.lower()"python"All lower case
"Hi " + word"Hi Python"Concatenation (join)
"ha" * 3"hahaha"Repeat
"th" in wordTrueIs it inside?
name = "Sofia"
for letter in name:
    print(letter)
S o f i a

A for loop can walk along a string one character at a time. Same loop, different thing to count through.

!Watch out

print("Score: " + 10) crashes: you can't join text and a number. Use "Score: " + str(10), or a comma: print("Score:", 10). The comma version adds a space for you.

e.g.Tidy input

answer = input("Yes or no? ").lower() means "YES", "Yes" and "yes" all become "yes". One line, and your if only has to check one spelling.

Three kinds of error

Every programmer makes errors every day. The skill is knowing which kind you have, because each kind shows up at a different time.

Before it runsWhile it runsAfter it finishes Syntax error Breaks the grammar rules.Nothing runs at all. print("Hi"missing ) if x > 3missing : Runtime error Grammar is fine, but a lineis impossible. It crashes there. print(10 / 0)ZeroDivisionError int("ten")ValueError Logic error Runs to the end with nomessage. The answer is wrong. avg = a + b / 2needs (a + b) / 2 if score > 40:40 should count: >=
Syntax errors are the easiest: Python tells you the line. Logic errors are the hardest: Python is happy, so you must notice the answer is wrong.
KindPython's messageCommon causesHow to find it
Syntax errorSyntaxError, IndentationErrorMissing : or ) or ", wrong indent, = instead of == in an ifRead the line Python points at, and the one above it
Runtime errorNameError, TypeError, ValueError, ZeroDivisionErrorTypo in a variable name, str + int, casting "ten", dividing by 0Read the last line of the red message: it names the problem
Logic errorNone!Wrong operator, > instead of >=, wrong order of if/elif, loop runs one time too manyTest with known answers, and trace the code (Step 11)
★Exams

AQA and OCR both ask for syntax and logic errors. "Runtime error" is extra, but Python shows them all the time, so students need it in practice. A trace table (Topic 11) is the exam tool for finding logic errors.

e.g.Read the error from the bottom

Python's red message ends with the useful bit: NameError: name 'scor' is not defined. Spot the typo, fix it, run again. Teach students to read the last line first.

Trace it line by line, then build it

Good programmers run code in their head before running it on the computer. Step through these programs. Watch which line runs, what's in each box, and what appears on screen.

▶

Mini Python tutor

Code
Variables (memory)
Screen

Predict first: before you press, say out loud what will change. (This is the "P" in PRIMM.)

The traffic-light build

The crossing-button traffic light uses everything on this page in one real program: variables (how many crossings), selection (was the button pressed?), iteration (the endless main loop, and a countdown).

# The same logic as the Arduino build, in Python
crossings = 0
while True:                      # iteration: for ever
    if button_pressed():         # selection
        crossings = crossings + 1    # variable
        lights("amber")
        lights("red")
        for s in range(5, 0, -1):    # countdown 5..1
            print(s)
    else:
        lights("green")
IdeaIn the build
SequenceAmber, then red, then countdown
Selectionif the button reads HIGH
IterationThe Arduino's loop() = while True; the countdown is a count-controlled loop
Variablecrossings goes up by 1 each press

Common mix-ups

The mistakes nearly every beginner makes. Read the left side, then the right.

People think

= means "is equal to".

Actually

= means store (assignment). == asks "are they equal?".

People think

input() gives a number if you type a number.

Actually

It always gives a string. Cast it: int(input()).

People think

range(1, 10) counts 1 to 10.

Actually

It stops before 10: 1 to 9, 9 numbers.

People think

A variable remembers how it was made, like a formula in a spreadsheet.

Actually

It holds a value. After b = a, changing a later does not change b.

People think

All the if, elif and else parts that are true will run.

Actually

Only the first true one runs. The rest are skipped.

People think

7 / 2 gives 3.

Actually

/ gives 3.5. Use // for 3 and % for the remainder 1.

People think

No error message means the program is right.

Actually

Logic errors give no message. Test with answers you already know.

Check yourself

Quick questions first. Then endless practice: a wrong answer shows you the working, step by step.

[ {"q":"What does print(\"3\" + \"4\") show?","o":["7","34","An error"],"a":1,"w":"They're strings, so + joins them: **34**."}, {"q":"What does 17 % 5 give?","o":["3","2","3.4"],"a":1,"w":"17 ÷ 5 = 3 remainder 2. % gives the remainder."}, {"q":"range(3) gives…","o":["1, 2, 3","0, 1, 2","0, 1, 2, 3"],"a":1,"w":"Starts at 0, stops before 3."}, {"q":"x = input(\"Number: \") and the user types 5. What type is x?","o":["int","str","float"],"a":1,"w":"input() always gives a **string**: \"5\". Cast it with int() to do maths."}, {"q":"How many times does for i in range(2, 10, 2): run?","o":["4","5","8"],"a":0,"w":"2, 4, 6, 8. The next would be 10, which is the stop, so it isn't used. **4** times."}, {"q":"score = 45. Code: if score >= 25: print(\"Bronze\") elif score >= 40: print(\"Gold\"). What prints?","o":["Gold","Bronze","Both"],"a":1,"w":"45 >= 25 is True, so the first branch runs and the rest is skipped. The order is wrong: a logic error."}, {"q":"A program runs with no message but says the average of 4 and 6 is 7. This is a…","o":["Syntax error","Runtime error","Logic error"],"a":2,"w":"It ran but gave the wrong answer: a **logic error**. (4 + 6 / 2 = 7; it needs brackets.)"}, {"q":"count = 5, then while count > 0: print(count). What happens?","o":["Prints 5 4 3 2 1","Prints 5 for ever","Prints nothing"],"a":1,"w":"Nothing changes count, so count > 0 stays True: an **infinite loop**."} ]