Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Caesar Cipher

Medium · 55 XP

Shift every lowercase letter in "hello world" forward by 3 (wrapping z→c), keep spaces, and print the result.

Target output
khoor zruog
Blank · autosaved
PYcaesar-cipher.py
Run your code to check it…
Guide

How to approach Caesar Cipher

Letters are characters, but shifting is arithmetic, so the trick is converting back and forth. ord(ch) turns a character into its number and chr(n) turns a number back into a character.

Subtracting ord("a") maps a to 0 through z to 25. Add the shift, take % 26 so that 26 wraps back to 0, then add ord("a") back. Spaces are not letters, so leave them exactly as they are.

Worked through on this data

  1. h is position 7. 7 + 3 = 10, which is k. The same move turns e into h and l into o, so "hello" becomes "khoor".
  2. w is position 22. 22 + 3 = 25, which is z. o becomes r, r becomes u, l becomes o, d becomes g: "zruog".
  3. The space passes through untouched, giving "khoor zruog". The wrap matters for letters near the end: z is 25, 25 + 3 = 28, and 28 % 26 = 2, which is c.

Common mistakes

  • Skipping % 26 works on this message by luck, but shifts z to a curly brace }.
  • Shifting the space as if it were a letter corrupts the word boundary.
  • Uppercase letters live at a different range (A is 65, a is 97). Handle them with their own base, or the output fills with symbols.

Time and space

One pass, constant work per character: O(n) time. Building a new string is O(n) space; collect characters in a list and "".join() them to avoid repeated string copies.

Where this shows up

Nobody protects data with a Caesar cipher today, but modular arithmetic on character codes is exactly how checksums, hash functions and ROT13 spoiler text work.

Take it further

Write decode(message, shift) and show that decoding the encoded text returns "hello world". Bonus: do both with str.maketrans and str.translate.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path