Encrypting a message with a Caesar loop in Python
Shifts an upper-case letter ch along the alphabet by shift, wrapping past Z back to A. A for loop applies it to each letter and builds the ciphertext with +=, skipping spaces.
Understanding Encrypting a message with a Caesar loop in Python in ACARA Digital Technologies Years 9–10
What it does: The += operator joins each shifted letter onto the end of result, so the ciphertext grows as the for loop runs. def creates a reusable function with the message (text) and the key (shift) as inputs, so the same loop works for any message. The - 65 turns A-Z into 0-25, % 26 wraps the number around, and + 65 turns it back into a letter. Without the wrap, Z would shift to a symbol, not a letter. Spaces and punctuation are not letters, so a Caesar cipher keeps them as they are. This is why we check with isalpha() first.
Common mistakes: Upper-case letters start at ord('A') = 65, so subtract 65 to get a position from 0 to 25. Subtracting 97 is for lower-case letters and would give negative numbers here. It should be n = ord(ch) - 65. range() needs a number, not a string, so this causes a TypeError. A for loop can go straight over the characters of the message: for ch in text:.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 860–875) and word search (Modules 860–944).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
chr((ord(ch) - 65 + shift) % 26 + 65)Fill in the Blanks
Spot the Error
Student with a class code? Join your class →