Nested Loops Mini Project — Caesar Cipher
The problem...
You've built the Caesar Cipher before. It shifted the alphabet and showed every letter's encrypted version.
But it didn't encrypt a real word. It just displayed the full shifted alphabet.
Time to make it actually useful.
The idea!
Now you have nested loops. Outer loop moves through every letter of the word. Inner loop moves through the alphabet to find the match and apply the shift.
Your mission
Ask the user for a word and a shift number. Encrypt the word — letter by letter — and print the result.
The solution
alphabet = "abcdefghijklmnopqrstuvwxyz"
word = input("Enter a word: ").lower()
shift = int(input("Enter shift number: "))
encrypted = ""
for letter in word:
for index, char in enumerate(alphabet):
if char == letter:
shifted_index = (index + shift) % 26
encrypted += alphabet[shifted_index]
break
print(f"Original: {word}")
print(f"Encrypted: {encrypted}")
Test it
# Enter a word: bull
# Enter shift number: 3
# Original: bull
# Encrypted: exoo
# Enter a word: horn
# Enter shift number: 13
# Original: horn
# Encrypted: ubea
What's really happening
The outer loop takes one letter from the word. The inner loop walks through the alphabet with enumerate() until it finds a match. When it does — it calculates the shifted position, adds the encrypted letter to the result, and breaks out of the inner loop. The outer loop moves to the next letter.
That's nested loops doing real work — outer sets the target, inner finds and processes it.
Go further
- Add decryption — ask the user if they want to encrypt or decrypt, shift in the opposite direction
- Handle spaces — skip them with
continueand add a space to the result - Try shift 13 — encrypt "bull", then encrypt the result again. What happens?
What you should understand now
- Outer loop sets the target — inner loop finds and processes it
breakinside the inner loop stops it — the outer loop keeps going+=builds the result string letter by letter- Nested loops make it possible to match items across two sequences