0
0
PythonProgramBeginner · 2 min read

Python Program to Implement Caesar Cipher

A Python program to implement Caesar cipher shifts each letter by a fixed number using chr((ord(char) - base + shift) % 26 + base) for letters; for example, def caesar_cipher(text, shift): return ''.join(chr((ord(c) - base + shift) % 26 + base) if c.isalpha() else c for c in text for base in [ord('A') if c.isupper() else ord('a')] if c.isalpha()).
📋

Examples

Inputtext='abc', shift=1
Outputbcd
Inputtext='Hello, World!', shift=3
OutputKhoor, Zruog!
Inputtext='xyz', shift=2
Outputzab
🧠

How to Think About It

To implement a Caesar cipher, think of each letter as a number from 0 to 25. You add the shift number to this value and wrap around if it goes past 25 using the remainder operator %. Non-letter characters stay the same. Then convert the number back to a letter.
📐

Algorithm

1
Get the input text and the shift number.
2
For each character in the text:
3
Check if it is a letter (uppercase or lowercase).
4
If it is a letter, convert it to a number 0-25, add the shift, and wrap around using modulo 26.
5
Convert the shifted number back to a letter, preserving case.
6
If it is not a letter, keep it unchanged.
7
Join all characters to form the encrypted text and return it.
💻

Code

python
def caesar_cipher(text, shift):
    result = []
    for char in text:
        if char.isalpha():
            base = ord('A') if char.isupper() else ord('a')
            shifted = (ord(char) - base + shift) % 26 + base
            result.append(chr(shifted))
        else:
            result.append(char)
    return ''.join(result)

print(caesar_cipher('Hello, World!', 3))
Output
Khoor, Zruog!
🔍

Dry Run

Let's trace 'Hello, World!' with shift 3 through the code

1

Check first character 'H'

'H' is uppercase, base = 65, ord('H')=72, shifted = (72-65+3)%26+65=75, chr(75)='K'

2

Check second character 'e'

'e' is lowercase, base = 97, ord('e')=101, shifted = (101-97+3)%26+97=104, chr(104)='h'

3

Check character ','

Not a letter, keep ',' as is

4

Continue for all characters

Apply same logic for each letter, keep punctuation unchanged

CharacterIsAlphaBaseOrdShifted OrdResult Char
HTrue657275K
eTrue97101104h
lTrue97108111o
lTrue97108111o
oTrue97111114r
,False---,
False---
WTrue658790Z
oTrue97111114r
rTrue97114117u
lTrue97108111o
dTrue97100103g
!False---!
💡

Why This Works

Step 1: Identify letters and base

We check if a character is a letter and find its base ASCII code: 65 for uppercase, 97 for lowercase.

Step 2: Shift letters with wrap-around

We convert the letter to a number 0-25, add the shift, then use modulo 26 to wrap around if needed.

Step 3: Convert back to character

We add the base back to the shifted number and convert it to a character to get the encrypted letter.

Step 4: Keep non-letters unchanged

Characters that are not letters, like spaces or punctuation, are added to the result without change.

🔄

Alternative Approaches

Using string translation with maketrans
python
def caesar_cipher(text, shift):
    import string
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    shifted_lower = lower[shift:] + lower[:shift]
    shifted_upper = upper[shift:] + upper[:shift]
    trans = str.maketrans(lower + upper, shifted_lower + shifted_upper)
    return text.translate(trans)

print(caesar_cipher('Hello, World!', 3))
This method is concise and fast but only works for English alphabets and fixed shifts.
Using list comprehension
python
def caesar_cipher(text, shift):
    return ''.join(
        chr((ord(c) - base + shift) % 26 + base) if c.isalpha() else c
        for c in text
        for base in [ord('A') if c.isupper() else ord('a')] if c.isalpha()
    )

print(caesar_cipher('Hello, World!', 3))
This approach is compact but may be harder to read for beginners.

Complexity: O(n) time, O(n) space

Time Complexity

The program processes each character once, so time grows linearly with input size.

Space Complexity

It creates a new string of the same length, so space grows linearly with input size.

Which Approach is Fastest?

Using string translation with maketrans is generally faster and more concise than manual character shifting.

ApproachTimeSpaceBest For
Manual shifting with ord/chrO(n)O(n)Learning and flexibility
String translation with maketransO(n)O(n)Performance and simplicity
List comprehensionO(n)O(n)Compact code but less readable
💡
Use modulo 26 to wrap shifts around the alphabet when implementing Caesar cipher.
⚠️
Forgetting to handle uppercase and lowercase letters separately causes wrong output.