Junior Computer Literacy · Data manipulation
Programming with Python
Write real Python programs that take input, calculate, make decisions, repeat, play sounds and roll dice. Every example runs right here on the slide, so you can change it and try again.
What does a program do?
A program is a list of instructions the computer follows in order. Most programs take input, process it, then give output.
Input
Process
Output
- In Python,
input()reads from the keyboard andprint()shows on the screen. - Python runs the lines from top to bottom, one at a time.
Output with print()
print() shows information on the screen. Text goes inside quotes; numbers and calculations do not.
print(3 + 4) → 7
print("3 + 4") → 3 + 4
print("Age", 13) → Age 13
- Commas print several items with a space between them.
+joins text with no space. Usestr()to turn a number into text first.sep=changes what goes between items;end=""stops print from starting a new line.\ninside text starts a new line.print()on its own prints a blank line.
+ and str() only.Input from the keyboard
input() shows a message, waits for the user to type and press Enter, then gives back what was typed.
age = int(input("Age: "))
height = float(input("Height (m): "))
input()always gives text (a string), even if you type a number.- Wrap it in
int()for whole numbers orfloat()for decimals before doing maths. - End the prompt with a space so the answer doesn't touch the question.
Variables: named boxes
A variable is a named box that stores a value. = means “put the value on the right into the box on the left”.
score = score + 10means: take the old score, add 10, store it back. It is an assignment, not a maths equation.- A box keeps only its latest value.
- Names: letters, digits and _, can't start with a digit, no spaces.
Scoreandscoreare different. - Choose names that explain themselves:
total_pricebeatstp.
age ✔ my score ✘ 2nd ✘ player_2 ✔ print ✘Arithmetic operators
Python can calculate with seven arithmetic operators. Change a and b to see every result.
**, then * / // %, then + -. Just like maths.Text or number? int(), float(), str()
Every value has a data type. The type decides what + does: numbers add, text joins.
| Type | Example | Change to it with |
|---|---|---|
| int (whole number) | 13, -5 | int("13") → 13 |
| float (decimal) | 1.58, 2.0 | float("1.58") → 1.58 |
| str (text) | "Ben", "13" | str(13) → "13" |
13 + 1 → 14
"13" + 1 → TypeError ✘
input() need int() or float(). Numbers joined to text with + need str().Example programs: input → process → output
Four short programs that use everything so far. Pick one, run it, then change it.
Challenge 1: rectangle
Add a line that prints the length of the diagonal. Hint: (length ** 2 + width ** 2) ** 0.5
Challenge 2: temperature
Write the reverse: °F to °C. c = (f - 32) * 5 / 9
Challenge 3: split the bill
Ask the user for the service charge percentage instead of always using 10%.
Challenge 4: minutes
Convert seconds into minutes and seconds using // and %.
# Input, # Process, # Output.Worked example: making change
Watch a program being built one step at a time: understand, plan, code each part, then test.
Exercises: input & variables
Climb the ladder: predict → complete → fix → modify → create. Each level gives a little less help.
Quick quiz: input & variables
Strings: join, repeat, measure
A string is text in quotes. Each character has a numbered position called an index, starting from 0.
"Ha" * 3 → "HaHaHa"
len("Hello") → 5
word[0] word[-1] word[0:3]
+joins strings;*repeats a string.len()counts characters, and spaces count too.word[-1]is the last character.word[a:b]takes from a up to, but not including, b.
String commands
Strings come with built-in commands (methods). Write the string, a dot, then the command: text.upper().
| Command | What it does |
|---|---|
upper() lower() title() | Change capital letters |
replace(a, b) | Swap every a for b |
count(x) find(x) | How many x; where x first appears (-1 if not found) |
center(n, "*") | Put text in the middle of n spaces |
text[::-1] | Reverse the text |
name = name.upper().Worked example: username maker
Slicing, string commands and joining work together to turn a name into a username.
Text with interesting effects
Mix print(), string commands, loops and time.sleep() to animate text on the screen.
import timethentime.sleep(0.5)pauses for half a second.print(x, end="", flush=True)prints on the same line and shows it immediately: the typewriter trick."*" * nand" " * nbuild bars, staircases and waves.center()makes neat banners.
for loop to repeat. We study loops properly in the next topic.Making sound
winsound.Beep(frequency, duration) plays a tone. Frequency is the pitch in hertz (Hz); duration is the length in milliseconds (1000 ms = 1 second).
- Start with
import winsound. It is built into Python on Windows computers. print("\a")rings the computer's bell in a terminal or Command Prompt.- Put notes in a list and loop through them to play a tune.
Extra: secret codes with ord() and chr()
Every character is stored as a number. ord("A") gives 65; chr(66) gives "B". Shift every letter by 3 and you have a Caesar cipher.
Exercises: text & sound
Climb the ladder: predict → complete → fix → modify → create.
Quick quiz: text & sound
Relational operators
A relational operator compares two values. The answer is always True or False (a Boolean).
| Meaning | Syllabus | Python |
|---|---|---|
| greater than | > | > |
| greater than or equal to | >= | >= |
| less than | < | < |
| less than or equal to | <= | <= |
| equal to | = | == |
| not equal to | <> | != |
= stores a value (assignment). To compare, use two: ==. The syllabus symbol <> is written != in Python.Logical operators: and, or, not
Logical operators combine True/False conditions. The syllabus writes AND, OR, NOT; Python writes them in lower case.
| Meaning | Syllabus | Python |
|---|---|---|
| True only if both are True | AND | and |
| True if at least one is True | OR | or |
| Flips True ↔ False | NOT | not |
Making decisions: if, elif, else
Flow control lets a program choose which lines to run. Python checks each condition from the top and runs the first block that is True.
- End the condition line with a colon
:. - Indent the lines inside by 4 spaces. Indentation shows which lines belong to the if.
elif= “else if”.elsecatches everything left, and needs no condition.
Nested if: a decision inside a decision
Put an if inside another if when the next question only makes sense after the first answer. The inner branch can even ask for new input().
- Each level of nesting adds 4 more spaces. Each
elselines up with its ownif. - The inner
input()only runs on that path, so users are never asked questions that don't apply to them. - If no new question is asked in between,
andis often simpler:if age >= 12 and height >= 140:
Worked example: cinema ticket (nested if)
A real pricing rule needs a decision, an extra question on one path, and an adjustment for everyone.
Loops in daily life
A loop repeats steps. Some loops repeat a fixed number of times (for); others repeat until a condition changes (while).
🏃Run 4 laps of the track
for Known number of times. for lap in range(4):
🪥Brush each tooth
for One repeat for each item in a set. for tooth in teeth:
⏰Alarm snooze
while Repeat while you are still asleep. while asleep:
🚦Traffic lights
while Red → green → amber, again and again, all day. while True:
🍜Stir the noodles until soft
while We don't know how many stirs; we check each time. while not soft:
🎵Sing the chorus 3 times
for Fixed count. for i in range(3):
🔐Phone passcode
while Keep asking until the code is right (or too many tries). while code != "1234":
🧺Washing machine rinse cycle
for The program rinses a set number of times. for rinse in range(3):
🎮Game: keep playing while you have lives
while while lives > 0:
Counting loops: for and range()
for i in range(start, stop, step): repeats the indented lines once for each number. The stop number is never included.
range(1, 6) → 1 2 3 4 5
range(2, 11, 2) → 2 4 6 8 10
range(5, 0, -1) → 5 4 3 2 1
- Use
forwhen you know how many times to repeat. - The loop variable (
i) takes each value in turn, so you can use it inside. for letter in "HELLO":loops over each character.
Condition loops: while
while condition: keeps repeating as long as the condition is True. Something inside the loop must change, or it never stops.
- The condition is checked before every repeat.
- Use
whilewhen you don't know how many repeats: passwords, games, “keep adding until 0”. - An infinite loop never ends. Press ■ Stop here, or Ctrl+C in IDLE.
n = n + 1 and run. What happens? Then press Stop.Simple programs with flow control and loops
Real programs combine if inside loops, counters and totals. Read each one and predict before you run it.
| Pattern | Code |
|---|---|
| Counter | count = count + 1 |
| Running total | total = total + mark |
| Flag | correct = True |
| Sentinel (stop value) | while item != "end": |
What does “3 tries” print if you type 1111, 2222, 1234?
Unlocked! The third guess is correct, so the loop ends with correct = True.
How would you change “Even numbers” to print the odd numbers?
range(1, 21, 2): start at 1 instead of 2.
What goes wrong in “Average mark” if you type 0 students?
ZeroDivisionError: total / 0. Fix it with if count > 0:.
Worked example: marks analyser
A loop with a running total, a counter and a “highest so far”: the three patterns behind most data programs.
Extra: patterns with nested loops and break
A loop inside a loop is a nested loop: the inner loop runs completely for every turn of the outer loop. break leaves a loop early.
for col in range(4):
print("*", end="")
print()
- Outer loop = rows; inner loop = items in each row.
print()after the inner loop moves to the next line.breakstops the loop as soon as we find what we want.
Exercises: decisions & loops
Eight exercises from predicting True/False to writing a nested if with input() inside and a loop with a counter.
Quick quiz: decisions & loops
Random numbers
A random number generator gives numbers we can't predict. Games, lucky draws and simulations all use it.
| Command | Gives |
|---|---|
import random | Load the random module (once, at the top) |
random.randint(1, 6) | A whole number from 1 to 6, both ends included |
random.random() | A decimal from 0 up to (not including) 1 |
random.choice(list) | One item picked from a list |
Observe randomness: is there a pattern?
With a few numbers, random results look uneven and streaky. With many, each value comes up about equally often, but we still can't predict the next one.
- Small sample: bars are very uneven. One number may not appear at all.
- Large sample: bars level out near the expected value. The average gets close to 3.5.
- Streaks happen. 6, 6, 6 is just as likely as 2, 5, 1.
Simulate a dice
One line does it: roll = random.randint(1, 6). Add if and loops to turn it into a game.
Arithmetic quiz generator
Random numbers + input() + if + a loop + a score variable = a quiz that is different every time.
b = random.randint(1, 10)
answer = int(input(...))
if answer == a + b:
score = score + 1
- Build the question with
str(a) + " x " + str(b), since there are no f-strings. random.choice(["+", "-", "x"])picks the operation;if/elifworks out the correct answer.
Exercises: random numbers & quizzes
From one line of random to a full calculator menu that combines while, if/elif and a nested if.
A variety of simple programming projects
Pick a project, load its starter code, run it, then complete the challenge to make it your own.
Extra: reading error messages
Errors are normal. The message tells you the line number and the type of problem. Fix each bug, then run again.
| Error | Usual cause |
|---|---|
| SyntaxError | Missing : ) or "; = instead of == |
| IndentationError | Lines inside if/for/while not indented |
| NameError | Spelling mistake, or text without quotes |
| TypeError | Joining text and a number with + |
| ValueError | int("abc"): not a number |
| ZeroDivisionError | Dividing by 0 |
Python playground
A blank space to live-code with the class. Everything from this set works here: input, print, maths, strings, sound, if, loops and random.
Quick quiz: random & projects
Python cheat sheet
Everything in this set on one page. Click Go to jump back to that slide.
Output
print("Hi", name)
print("Total: " + str(t))
print("A", end="")Input
name = input("Name: ")
n = int(input("Number: "))
x = float(input("Price: "))Variables & maths
score = score + 1 + - * / // % **
Strings
"Ha" * 3 len(s) s[0]
s.upper() s.replace("a", "b")
s.center(20, "*") s[::-1]Effects & sound
import time, winsound time.sleep(0.5) winsound.Beep(440, 500)
Compare & combine
> >= < <= == != syllabus = → == <> → != AND OR NOT → and or not
Decisions
if mark >= 80:
print("A")
elif mark >= 50:
print("Pass")
else:
print("Fail")Nested if
if user == "admin":
pw = input("Password: ")
if pw == "py123":
print("Welcome")
else:
print("Wrong")Loops
for i in range(1, 11):
print(i)
while answer != "yes":
answer = input("? ")Random
import random roll = random.randint(1, 6) pick = random.choice(names)
Suggested lesson plan
About eleven 40-minute lessons, plus 2–3 lessons for a mini project. Click a slide name to jump there.
| Lesson | Syllabus point | Slides | Student task |
|---|---|---|---|
| 1 | Input and output | Greeting program with their own questions | |
| 2 | Variables and arithmetic in assignment | Challenges 1–4 on the examples slide | |
| 3 | Worked example and practice | Exercise levels 1–5 | |
| 4 | Manipulate text; effects; sound | Name banner + a short tune | |
| 5 | Practice: text and sound | Exercise levels 1–5 | |
| 6 | Relational and logical operators; if | Ride checker, grade program | |
| 7 | Nested if with input | Test table for every path | |
| 8 | Daily-life loops; for and while | Times table, password loop | |
| 9 | Simple programs with flow control and loops | Bus fare (nested if), hot days | |
| 10 | Random numbers, pattern, dice | Dice counter with 600 rolls | |
| 11 | Arithmetic quiz | 5-question quiz with score; calculator menu | |
| 12–14 | A variety of simple projects | Pair project and short demo to the class |