livepython.net

229. Python Program to Hide a Message with a Caesar Cipher

HardPhase 3 · Challenge

This one takes a few steps. It uses find(), the % sign and a for loop over a string, and you know all three. Try a short word on paper first.

Overview

A cipher is a secret way of writing a message. The Caesar cipher is one of the oldest: Julius Caesar used it more than 2000 years ago. Writing it is a common interview question.

Problem Statement

Felix and Rania pass secret notes in class. They hide each note with a Caesar cipher.

To hide a message, you move each letter forward in the alphabet by the same number of places. This number is called the shift. With a shift of 3, a becomes d, b becomes e, and so on.

The rules:

  • After z, start again at a. With a shift of 3, x becomes a, y becomes b and z becomes c.
  • Keep the case. A capital letter stays a capital letter: with a shift of 3, A becomes D.
  • Keep every other character as it is: spaces, digits and punctuation do not change.
  • Only the 26 letters from a to z and from A to Z move.

A shift of 26 moves each letter all the way round, back to itself. So a shift of 27 works like a shift of 1.

Read the message and the shift. Print Hidden message: <message>.

Examples

Example 1. Input:

Hello, World
3

gives:

Hidden message: Khoor, Zruog

Why: each letter moves 3 places: H to K, e to h, l to o and o to r. The comma and the space stay as they are.

Example 2. Input:

xyz
2

gives:

Hidden message: zab

Why: x moves 2 places to z. y moves past z and starts again at a. In the same way, z becomes b.

Input

  • Line 1: the message, 1 character or more. It does not start or end with a space.
  • Line 2: the shift, a whole number from 0 to 100.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Hidden message:, a space and the hidden message. The tests try 10 different inputs, also a shift of 0, a shift of 26 and shifts bigger than 26.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Hidden message: Khoor, Zruog

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.