Improving the Caesar cipher
Improving the Caesar Cipher |
Level of difficulty
HardPre-requisites
Module 1.11.1.1, Module 1.11.1.2Objectives
- 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 data
Sample input:
abcxyzABCxyz 1232
Sample output:
cdezabCDEzab 123Sample input:
The die is cast25
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))
Follow our python page for more
0 Comments
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.