Programming with Python

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.

← → or PgUp PgDn change slide O all slidesN teacher notesT timerF full screenCtrl+Enter run codeEsc leave the code box so arrows move slides 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 and print() 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("Hello") → Hello
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. Use str() to turn a number into text first.
  • sep= changes what goes between items; end="" stops print from starting a new line.
  • \n inside text starts a new line. print() on its own prints a blank line.
No f-stringsIn this course we join output with commas, + 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.

name = input("What is your name? ")
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 or float() for decimals before doing maths.
  • End the prompt with a space so the answer doesn't touch the question.
Try itRun The text trap and type 3 and 4. Why do we get 34?

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 + 10 means: 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. Score and score are different.
  • Choose names that explain themselves: total_price beats tp.
Good or bad name?age ✔   my score ✘   2nd ✘   player_2 ✔   print ✘
Step through the programPress Step and watch the boxes

Arithmetic operators

Python can calculate with seven arithmetic operators. Change a and b to see every result.

Operator explorerTry b = 0, or a negative a
Order of operationsBrackets first, then **, 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.

TypeExampleChange to it with
int (whole number)13, -5int("13") → 13
float (decimal)1.58, 2.0float("1.58") → 1.58
str (text)"Ben", "13"str(13) → "13"
"13" + "1" → "131"
13 + 1 → 14
"13" + 1 → TypeError ✘
Rule of thumbNumbers from 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 %.

Plan before you codeWrite the three parts as comments first: # Input, # Process, # Output.

Worked example: making change

Watch a program being built one step at a time: understand, plan, code each part, then test.

Build it step by stepPress Next step

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.

String explorerClick a letter, drag the sliders
"Ice" + "cream" → "Icecream"
"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 playgroundClick a command

CommandWhat 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
NoteCommands make a new string. To keep the change, store it: name = name.upper().

Worked example: username maker

Slicing, string commands and joining work together to turn a name into a username.

Build it step by stepPress Next step

Text with interesting effects

Mix print(), string commands, loops and time.sleep() to animate text on the screen.

  • import time then time.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.
  • "*" * n and " " * n build bars, staircases and waves.
  • center() makes neat banners.
Loops previewThese effects use a 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).

Piano to PythonPlay keys, then send your tune to the code box
winsound.Beep(262, 300)
Higher number = higher pitchDoubling the frequency plays the same note one octave higher: 262 → 524.
  • 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.

Caesar wheelChange the shift

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).

MeaningSyllabusPython
greater than>>
greater than or equal to>=>=
less than<<
less than or equal to<=<=
equal to===
not equal to<>!=
Watch outIn Python, a single = stores a value (assignment). To compare, use two: ==. The syllabus symbol <> is written != in Python.
Comparison machineMake them equal

Logical operators: and, or, not

Logical operators combine True/False conditions. The syllabus writes AND, OR, NOT; Python writes them in lower case.

MeaningSyllabusPython
True only if both are TrueANDand
True if at least one is TrueORor
Flips True ↔ FalseNOTnot
Truth switch boardClick A and B
Can I ride the roller coaster?Rule: age ≥ 12 and height ≥ 140

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.

Follow the flowchartDrag the mark
Start input mark mark >= 80? mark >= 50? print Excellent! print Pass print Try again End YesNo YesNo
  • 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”. else catches 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().

Path explorerChoose the answers
Username
Password
if first question: # 0 spaces answer = input(...) # 4 spaces if second question: # 4 spaces print(...) # 8 spaces else: print(...) else: print(...)
  • Each level of nesting adds 4 more spaces. Each else lines up with its own if.
  • 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, and is 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.

Build it step by stepPress Next step

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:

Your turnThink of one more loop at home or at school. Is it a counting loop (for) or a condition loop (while)?

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() visualiserTry a negative step

range(5) → 0 1 2 3 4
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 for when 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.

Step through a while loopWatch n and total
  • The condition is checked before every repeat.
  • Use while when 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.
Try itIn “Add 1 to 4”, delete the line 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.

PatternCode
Countercount = count + 1
Running totaltotal = total + mark
Flagcorrect = 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.

Build it step by stepPress Next step

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 row in range(3):
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.
  • break stops 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.

CommandGives
import randomLoad 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
Did you know?Computers follow rules, so their random numbers are really pseudo-random: a clever formula that looks random.
Generate a set of integersGenerate twice. Same numbers?

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.

Random lab: numbers 1 to 610 → 100 → 10000
Expected each
Most / least
Longest streak
Average
  • 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.
DiscussAfter four 6s in a row, is the next roll less likely to be a 6? (No, each roll is independent.)

Simulate a dice

One line does it: roll = random.randint(1, 6). Add if and loops to turn it into a game.

Dice simulatorRoll, then roll 600 times

Arithmetic quiz generator

Random numbers + input() + if + a loop + a score variable = a quiz that is different every time.

Class challengeType the answer and press Enter
a = random.randint(1, 10)
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/elif works 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.

Project checklist1. Plan input, process, output. 2. Write and test a small part first. 3. Test with normal, boundary and silly inputs. 4. Add comments. 5. Ask a friend to try it.

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.

ErrorUsual cause
SyntaxErrorMissing : ) or "; = instead of ==
IndentationErrorLines inside if/for/while not indented
NameErrorSpelling mistake, or text without quotes
TypeErrorJoining text and a number with +
ValueErrorint("abc"): not a number
ZeroDivisionErrorDividing 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)
Exit questionPlan a program that rolls two dice 100 times and counts how many doubles appear. Which commands from this page would you need?

Suggested lesson plan

About eleven 40-minute lessons, plus 2–3 lessons for a mini project. Click a slide name to jump there.

LessonSyllabus pointSlidesStudent task
1Input and outputGreeting program with their own questions
2Variables and arithmetic in assignmentChallenges 1–4 on the examples slide
3Worked example and practiceExercise levels 1–5
4Manipulate text; effects; soundName banner + a short tune
5Practice: text and soundExercise levels 1–5
6Relational and logical operators; ifRide checker, grade program
7Nested if with inputTest table for every path
8Daily-life loops; for and whileTimes table, password loop
9Simple programs with flow control and loopsBus fare (nested if), hot days
10Random numbers, pattern, diceDice counter with 600 rolls
11Arithmetic quiz5-question quiz with score; calculator menu
12–14A variety of simple projectsPair project and short demo to the class
Computer room setupStudents can type the same code into IDLE (comes with Python from python.org) or Thonny. winsound works on Windows only; on other computers use print("\a") or skip sound. This deck runs Python inside the page, so it also works on the teacher's computer without installing anything.