Encrypting and decrypting with a one-time pad in Python
One-time pad: shift each message letter number m by the matching key number k, wrapping with % 26. To decrypt, subtract the same key values: (c - k) % 26. zip pairs each letter with its key.
Understanding Encrypting and decrypting with a one-time pad in Python in QCE Digital Solutions Unit 4
What it does: zip(message, key) gives one letter and one key value at a time, so each letter is shifted by its own matching key number. Subtracting k undoes the encryption shift. ord(ch) - 65 converts the letter to 0-25, and % 26 wraps the result back into the alphabet. Decryption reverses the shift, so you subtract the same key value and wrap with % 26. 29 is outside 0-25. The % 26 wraps it around to 3, which is the letter 'D'. Python's % always gives a result from 0 to 25 when the divisor is 26, so (2 - 5) % 26 is 23. This is why decryption still works for small cipher numbers.
Common mistakes: zip needs both lists to pair each message number m with its key number k. zip(msg) gives single items that cannot be unpacked into m, k. It should be zip(msg, key). The alphabet has 26 letters, so the wrap-around must use % 26. Using % 25 gives the wrong cipher numbers. It should be (m + k) % 26.
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 334–401) and word search (Modules 127–401).
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
(m + k) % 26Fill in the Blanks
Spot the Error
Student with a class code? Join your class →