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.
| Scratch | Python | What it does |
|---|---|---|
| say [Hello] | print("Hello") | Show something on screen |
| ask [Name?] and wait | name = input("Name? ") | Get typed input |
| set [score] to 0 | score = 0 | Assignment |
| change [score] by 1 | score = score + 1 | Update a variable |
| if … then … else | if …: / else: | Selection |
| repeat 10 | for i in range(10): | Count-controlled loop |
| repeat until … | while not …: | Condition-controlled loop |
| forever | while True: | Loop for ever |
| pick random 1 to 10 | random.randint(1, 10) | Random whole number (needs import random) |
Sequence: top to bottom
print("Hello")
print("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 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
| Idea | Python | AQA 8525 pseudocode | OCR J277 reference language |
|---|---|---|---|
| Assignment | score = 0 | score ← 0 | score = 0 |
| Output | print(score) | OUTPUT score | print(score) |
| Input | name = input() | name ← USERINPUT | name = input() |
| Count loop | for i in range(1, 11): | FOR i ← 1 TO 10 … ENDFOR | for i = 1 to 10 … next i |
| DIV / MOD | 7 // 2 · 7 % 2 | 7 DIV 2 · 7 MOD 2 | 7 DIV 2 · 7 MOD 2 |
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: make a box called score, put 0 in it. This is assignment.score = score + 10: read the right side first. 0 + 10 = 10. Put 10 back in the box.print(score)shows 10. No quotes: it shows what's in the box, not the word "score".
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".
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.
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.
| Type | Holds | Python examples | In memory (Topics 3–4) |
|---|---|---|---|
Integer (int) | Whole numbers | 7, -3, 0 | Binary number (two's complement for negatives) |
Float (float) | Decimal numbers | 3.14, 0.5, 7.0 | A 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 False | True, False | Could 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.
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))
input()always gives back a string, even if you type digits. Type 13 and you get "13".int()turns "13" into 13 so you can do maths. Changing type is casting.float("2.5")andstr(14)are casting too.str()turns 14 back into text so it can be joined to other text with+.
age = input("Age? ") # you type 13
print(age + 1)age = int(input("Age? ")) # 13
print(age + 1)"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 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).
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Add | 7 + 2 | 9 |
| - | Subtract | 7 - 2 | 5 |
| * | Multiply | 7 * 2 | 14 |
| / | Divide (always gives a float) | 7 / 2 · 6 / 2 | 3.5 · 3.0 |
| // | Whole-number divide (DIV) | 7 // 2 | 3 |
| % | Remainder (MOD) | 7 % 2 | 1 |
| ** | Power | 2 ** 8 | 256 |
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
How many 5s fit into 17? Count up in 5s: 5, 10, 15. The next one, 20, is too big.
Three 5s fit. So 17 // 5 = 3. That's DIV.
Three 5s make 15. What's left? 17 − 15 = 2. So 17 % 5 = 2. That's MOD.
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")
| n | n // 2 | n % 2 | Even? |
|---|---|---|---|
| 6 | 3 | 0 | Yes |
| 7 | 3 | 1 | No |
| 10 | 5 | 0 | Yes |
| 13 | 6 | 1 | No |
Even numbers split into 2 with nothing left, so n % 2 is 0. Odd numbers always leave 1.
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.
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.
| Operator | Meaning | Example | Answer |
|---|---|---|---|
| == | Equal to | 5 == 3 | False |
| != | Not equal to | 5 != 3 | True |
| > < | Greater than / less than | 5 > 3 | True |
| >= <= | Greater / less than or equal | 5 <= 3 | False |
Join questions with and, or, not. These are the logic gates from Topic 9.
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| False | False | False | False | True |
| False | True | False | True | True |
| True | False | False | True | False |
| True | True | True | True | False |
The code:
age = 13, thenif age >= 11 and age <= 14:Swap in the value:
13 >= 11 and 13 <= 14.Work out each side:
True and True.andneeds both sides True. They are, so the answer is True: age 13 is in KS3.
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.
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")
Check the
if. True? Run its indented lines and skip the rest.False? Check the
elif("else if"). You can have as many elifs as you like.Nothing true? Run the
else. It has no condition: it catches everything left.
| score | score >= 40? | score >= 25? | Output |
|---|---|---|---|
| 45 | True | not checked | Gold badge! |
| 40 | True | not checked | Gold badge! |
| 30 | False | True | Bronze badge |
| 12 | False | False | Try the Respawn quest |
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.
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.
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)
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.
| Code | Numbers | Times it runs |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | 5 |
| range(1, 6) | 1, 2, 3, 4, 5 | 5 |
| range(2, 10, 3) | 2, 5, 8 | 3 |
| range(10, 0, -2) | 10, 8, 6, 4, 2 | 5 |
| range(5, 5) | (nothing) | 0 |
range() visualiser
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.
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!")
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.
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.
| for | while | |
|---|---|---|
| Type of loop | Count-controlled | Condition-controlled |
| Use when | You know how many times | You repeat until something happens |
| Scratch | repeat 10 | repeat until … (Python: while not …) · forever (while True) |
| Can it be infinite? | No (range always ends) | Yes, if the condition never becomes False |
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") | Result | What it does |
|---|---|---|
| len(word) | 6 | How 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 word | True | Is it inside? |
name = "Sofia"
for letter in name:
print(letter)
A for loop can walk along a string one character at a time. Same loop, different thing to count through.
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.
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.
| Kind | Python's message | Common causes | How to find it |
|---|---|---|---|
| Syntax error | SyntaxError, IndentationError | Missing : or ) or ", wrong indent, = instead of == in an if | Read the line Python points at, and the one above it |
| Runtime error | NameError, TypeError, ValueError, ZeroDivisionError | Typo in a variable name, str + int, casting "ten", dividing by 0 | Read the last line of the red message: it names the problem |
| Logic error | None! | Wrong operator, > instead of >=, wrong order of if/elif, loop runs one time too many | Test with known answers, and trace the code (Step 11) |
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.
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
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")
| Idea | In the build |
|---|---|
| Sequence | Amber, then red, then countdown |
| Selection | if the button reads HIGH |
| Iteration | The Arduino's loop() = while True; the countdown is a count-controlled loop |
| Variable | crossings goes up by 1 each press |
Common mix-ups
The mistakes nearly every beginner makes. Read the left side, then the right.
= means "is equal to".
= means store (assignment). == asks "are they equal?".
input() gives a number if you type a number.
It always gives a string. Cast it: int(input()).
range(1, 10) counts 1 to 10.
It stops before 10: 1 to 9, 9 numbers.
A variable remembers how it was made, like a formula in a spreadsheet.
It holds a value. After b = a, changing a later does not change b.
All the if, elif and else parts that are true will run.
Only the first true one runs. The rest are skipped.
7 / 2 gives 3.
/ gives 3.5. Use // for 3 and % for the remainder 1.
No error message means the program is right.
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.