FOR Mini Project — Caesar Cipher
The problem...
Julius Caesar encrypted his messages by shifting every letter a fixed number of positions in the alphabet.
A becomes D. B becomes E. C becomes F. With a shift of 3.
Simple. Effective. And a perfect job for a for loop.
The idea!
You loop through the alphabet. For each letter, you find its shifted position using range() and enumerate(). You print the original and the encrypted version side by side.
The alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
Just a string. All 26 letters. That's all you need.
Your mission
Ask the user for a shift number. Loop through the alphabet and print each letter paired with its Caesar-shifted equivalent.
The solution
import string
alphabet = string.ascii_lowercase
shift = int(input("Enter shift number: "))
for index, letter in enumerate(alphabet):
shifted_index = (index + shift) % 26
shifted_letter = alphabet[shifted_index]
print(f"{letter} -> {shifted_letter}")
What's really happening
enumerate() gives you the position and the letter at the same time.
(index + shift) % 26 shifts the position forward — and wraps around when it goes past Z. % is the modulo operator you saw in Basics — the remainder after division.
# shift = 3
# a (0) -> d (3)
# x (23) -> a (0) — wraps around
# z (25) -> c (2) — wraps around
Test it
# Enter shift number: 3
# a -> d
# b -> e
# c -> f
# ...
# x -> a
# y -> b
# z -> c
Go further
- Try shift 13 — that's ROT13, a famous cipher used on the internet
- Try shift 26 — what happens? Why?
- Try a negative shift — does it work?
What you should understand now
enumerate()gives position and value — useful when you need both% 26wraps the index around — no going out of boundsimportloads ready-made tools — more on this later- A
forloop can process every character in a string automatically