Fancy sending a secret note to your friends/secret lover/spouse? In this Python tutorial, we are going to go through a simple program that allows you to do just that. Before we start, this tutorial assumes you have knowledge of the concepts covered in my book Python (2nd Edition): Learn Python in One Day and Learn It Well.
Specifically, you need to know:
- How to use the range() function to read a string
- How to accept user input and print output to the screen
- How to manipulate strings (e.g. Concatenate two strings)
- How to use the while and if statements
Before we start coding our program, we have to first briefly explain what Unicode is, as this concept forms a major component in our encryption/decryption program.
Simply stated, Unicode is a computing industry standard for the consistent encoding, representation, and handling of text. Fundamentally, computers can only deal with numbers. Hence, in order for them to interpret letters like ‘A’ or characters like ‘@’, these letters and characters have to be translated into numbers.
Unicode is the standard used for such translation. Every character in every language has a unique Unicode code point assigned to it. For instance, the letter ‘A’ has Unicode U+0041
.
This code is then further encoded into binary numbers before it is stored in the computer. The most commonly used encoding is UTF-8. The UTF-8 representation for ‘A’ is the number 65.
Do not worry if you do not quite grasp the concept of Unicode or UTF encoding. For the purpose of this tutorial, all you have to know is that letters and characters are mapped into integers (numbers with no decimal parts) before being stored in the computer.
Python provides 2 built-in functions for us to change letters and characters into Unicode representations and vice versa. The first function ord()
converts a character into an integer representing the Unicode of that character. The second function chr()
does the reverse. Hence, ord('A')
will give us 65 while chr(65)
will return the character ‘A’.
Equipped with this basic knowledge of Unicode, we are now ready to write our ‘Enigma machine’.
The full code is:
result = '' message = '' choice = '' while choice != '-1': choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ") if choice == '1': message = input("\nEnter the message to encrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) - 2) print (result + '\n\n') result = '' elif choice == '2': message = input("\nEnter the message to decrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) + 2) print (result + '\n\n') result = '' elif choice != '-1': print ("You have entered an invalid choice. Please try again.\n\n")
Dissecting the Code
First, let’s declare three variables result
, message
and choice
and assign them the empty string.
result = '' message = '' choice = ''
Next, on line 5 and 6, we use the while-loop
to repeatedly prompt users to select whether they want to encrypt or decrypt the message. Alternatively, they can enter ‘-1’ to exit the program.
while choice != '-1': choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
Next, we’ll use a if-statement
to determine what to do based on the value of choice
.
if choice == '1': message = input("\nEnter the message to encrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) - 2) print (result + '\n\n') result = ''
If choice
is 1 (line 8), we’ll ask them to enter the message to encrypt.
We then loop through the message character-by-character using the range()
function on line 11.
On line 12, we use ord(message[i])
to get the numerical representation of the character and subtract two from that number. For instance, if the character is ‘D’, ord(message[i])
will return 68. When we subtract 2, we’ll get 66, which is the numerical representation for ‘B’. We then convert 66 to ‘B’ using the chr()
function.
Finally, we concatenate the resulting character ‘B’ to the string variable result
.
The table below shows how this works in greater detail. Suppose we start off with the string ‘Python’. Here’s what happens as the program loops through the word ‘Python’ to get the resulting encrypted message ‘Nwrfml’:
Finally, after encrypting the message, the next two lines (14 and 15) print the string result
and reset the result
variable back to an empty string.
That’s it. That’s how we can write a simple encryption program. The next few lines (17 to 24) does the reverse and decrypts our message by adding 2 to the numerical representation of our message.
elif choice == '2': message = input("\nEnter the message to decrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) + 2) print (result + '\n\n') result = '' elif choice != '-1': print ("You have entered an invalid choice. Please try again.\n\n")
Finally, the last two lines (26 and 27) inform our users that they have entered an invalid choice if they entered a number other than 1, 2 or -1.
Note that on line 26 we don’t have to write if choice != '1' and choice != '2' and choice != '-1'
although we can if we prefer. This is because the very fact that the program reached line 26 means the user did not enter 1 or 2. Else, the program would have executed either lines 5 to 15 or 17 to 24.
That’s all for today’s tutorial. I hope it has been useful to you. You can download the source code here. Do leave a comment if you have any questions or feedback. If you enjoyed the post, please help by sharing it.
Have fun coding and talk again soon!