Improving the Caesar cipher
 |
| Improving the Caesar Cipher |
Level of difficulty
Hard
Pre-requisites
Module 1.11.1.1, Module 1.11.1.2
Objectives
- improving the student's skills in operating with strings;
- converting characters into ASCII code, and vice versa.
Scenario
You are already familiar with the Caesar cipher, and this is why we want you to improve the code we showed you recently.
The original Caesar cipher shifts each character by one:
a becomes
b,
z becomes
a, and so on. Let's make it a bit harder, and
allow the shifted value to come from the range 1..25 inclusive.
Moreover,
let the code preserve the letters' case (lower-case letters will remain lower-case) and all non-alphabetical characters should remain untouched.Your task is to write a program which:
- asks the user for one line of text to encrypt;
- asks the user for a shift value (an integer number from the range 1..25 - note: you should force the user to enter a valid shift value (don't give up and don't let bad data fool you!)
- prints out the encoded text.
Test your code using the data we've provided.
Test data
Sample input:
abcxyzABCxyz 123
2
Sample output:
cdezabCDEzab 123
Sample input:
The die is cast
25
Sample output:
Sgd chd hr bzrs
Solution Code:
Now, if you are looking for a ready code, below you will find it (but coding is not about ready solutions). And if you are looking forward to learn and enhance your python coding skills and knowledge, please let me know in the comments and I will tell you how this code has been built.
text = input("Enter your message: ")
shift_value = int(input("Please Enter a Shift Value from 1 - 25: "))
def encryped(text , shift_value):
cipher = ''
for char in text:
if char == ' ':
cipher += char
elif char.isdigit():
cipher += char
elif char.isupper():
cipher += chr((ord(char) + shift_value - 65) % 26 + 65)
else:
cipher += chr((ord(char) + shift_value - 97) % 26 + 97)
return cipher
print("The Encrypted string is:\n ", encryped(text, shift_value))
citation
Python, K. I. (2019, October 14). Encryption of message with ceasor cipher algorithm using python. YouTube. Retrieved January 27, 2022, from https://www.youtube.com/watch?v=Ws5E2gCW4Hc&feature=youtu.be
How the Improved Caesar Cipher Shifts Text
This lab improves the basic Caesar cipher so it accepts a shift value anywhere from 1 to 25 inclusive, rather than always shifting by one. Where the original code made a become b and z become a, the improved version lets a chosen shift_value control how many positions each letter moves around the alphabet. To keep the encryption realistic, it must preserve letter case and leave every non-alphabetical character untouched, so punctuation, spaces, and digits pass through unchanged.
The solution processes the input text character by character. For a space it simply appends the space, and for a digit it uses char.isdigit() to keep the digit as-is. For actual letters, the code converts each character to its ASCII code with ord(char), applies the shift, and wraps the result back around the alphabet using modulo before turning it into a character again with chr().
Wrapping within the Alphabet with Modulo
For uppercase letters, whose ASCII codes run from 65 ('A') to 90 ('Z'), the formula is chr((ord(char) + shift_value - 65) % 26 + 65). Subtraction of 65 normalizes a letter to a 0..25 index, the shift and the % 26 wrap the index around the alphabet, and adding 65 maps the result back into the ASCII uppercase range. Lowercase letters use 97 instead of 65 because 'a' has ASCII code 97. This is why shifting "abcxyzABCxyz 123" by 2 produces "cdezabCDEzab 123", and why shifting "The die is cast" by 25 moves every letter one step backward to "Sgd chd hr bzrs".
Key Takeaways
- The improved cipher accepts a shift value in the range 1..25 instead of always shifting by one.
- Every alphabetical character is shifted while its case is preserved.
- Non-alphabetical characters such as spaces and digits remain unchanged.
ord(char) converts a character to its ASCII code, and chr() converts a code back to a character.
- The
% 26 operation wraps shifted letters around the end of the alphabet.
- Uppercase letters use the 65-based formula while lowercase letters use 97 to match their ASCII ranges.
Frequently Asked Questions
Why is modulo 26 used in the shift?
Because there are 26 letters in the alphabet, and modulo keeps a shifted index inside the 0..25 range so letters wrap from z back to a.
Why are 65 and 97 subtracted and added back?
They are the ASCII codes of 'A' and 'a'. Subtracting them normalizes a letter to a 0-based index, and adding them back restores the correct uppercase or lowercase range.
How does the code preserve letter case?
It checks char.isupper() and uses the uppercase-based formula for capital letters, while lowercase letters fall into the else branch that uses 97.
What happens to non-letters like spaces and numbers?
They are appended unchanged because the code branches on a space and char.isdigit() before applying any shifting to letters.
Comments
Post a Comment
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.