Vigenere cipher in Python
Picks the keyword letter for position i and wraps back to the start with %, so each message letter gets its own shift. This is how a Vigenere cipher loop cycles the keyword.
Understanding Vigenere cipher in Python in ACARA Digital Technologies Years 9–10
What it does: Using j instead of i means spaces and punctuation do not advance the keyword, so the keyword stays lined up with the letters. Decrypting reverses encrypting. Subtracting the shift undoes it, and % 26 keeps the result inside the alphabet. 4 % 3 = 1, so the index wraps back to the start and picks key[1], which is A. The % operator makes the keyword cycle. Without %, key[i] would cause an IndexError once i passed the end of the keyword. The % keeps the index inside the keyword. key[0] always gives the first keyword letter, so every letter gets the same shift. That is a Caesar cipher, not a Vigenere cipher.
Common mistakes: / gives a decimal, which cannot be used as an index. Use % so i wraps back to the start of the keyword: key[i % len(key)]. The shift is the keyword letter's position in the alphabet (A=0 to Z=25), so you subtract 65: ord(s) - 65. Adding 65 gives a huge, wrong shift.
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 876–944) 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
key[i % len(key)]Fill in the Blanks
Spot the Error
Student with a class code? Join your class →