python

[Tutorial] Make your own Python decoder with the HyperionDev free trial

Posted by

In this blog – a follow-on from our last Free Trial Beginner Coding Tutorial – we look at the kinds of programs that a newcomer to coding can make using just our free trial and the programming essentials. This time, we’re making a fun secret encoder/decoder program in Python, to write and decipher secret messages using just the basics that are taught in our HyperionDev free trial. 

Let’s begin!

Step 1: Set up what you’ll need

First off, you and your secret accomplice need to decide on a secret codebook, which you’ll use to encrypt or decipher the meanings of your messages. We can do this by creating two lists: one with the normal alphabet, and another with random letters in a jumbled-up order. Remember that a list is just a group of variables combined in a single collection through the use of square brackets. We’ll use these two lists to create a secret codebook.

Let’s declare these lists in our program.

normal = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "]
secret = ["D", "N", "B", "M", "I", "F", "L", "Q", "H", "Y", "R", "P", "E", "V", "A", "W", "Z", "O", "K", "J", "T", "X", "U", "C", "S", "G", " "]

Now, lists are useful, but it can be clunky to iterate through a list to find one character, grab its index, and then fetch an address from a second list. It would be so much easier if each letter of the alphabet had a corresponding partner value… Luckily, Python does this, with a really useful thing called dictionaries! Dictionaries – denoted by curly brackets “{}” – pair up two variables in a particular manner. It’s simpler to just go through a dictionary, find the letter we’re looking for (which will be the ‘key’  in the dictionary) and return its associated value. 

Let’s combine our alphabet list with our secret list into one single dictionary. We can do this by using a ‘for’ statement that creates key-value pairs by cycling through a zip object that combines both lists into one object. A ‘for’ statement is a simple loop that allows you to run a certain function or do something with each element in a given collection of data.

Of course, we’ll need to create two dictionaries, one to encrypt normal letters, and another to decrypt the secret letters.

EncryptionKeybase = {key:value for key, value in zip(normal, secret)}
DecoderKeybase = {key:value for key, value in zip(secret, normal)}

Step 2: Write your code for encrypting or decoding 

Now that we have our secret codebook, let’s create the functions that will encrypt or decode your message. 

We have a few options here. We could make a loop that runs twice to check each letter in each key-value assignment, however, running two separate loops can be confusing to keep track of, so it’s much easier to just run one single ‘for’ statement to iterate through the message the user types in and return the value from the appropriate corresponding key (here, a letter of the alphabet).

We will create two functions that we’ll use to encrypt or decode our secret message.

Both of these functions will receive a string as a parameter, here named “message”. We’ll get this “message” from the user later.

Step 3: Make sure you’re handling exceptions and errors

Now, before we type in any code, we have to imagine what kinds of messages the user might try to send – does our code account for all scenarios? What happens if they type a number, or a special character? We need to make sure that our code won’t miss these outliers, or break if the user includes them in their message. Also, the keys in a dictionary are case-sensitive, so let’s ensure that our code converts the inputted messaging into uppercase to match the list items we made at the very beginning. To do this, we’ll use an ‘if’ statement to check if the message is in the uppercase, with Python’s .isupper()  method. If this returns as false, we make the inputted message uppercase. 

def encrypt_message(message):
 uppermessage = ""
 if message.isupper() != True:
   uppermessage = message.upper()
 elif message.isupper() == True:
   uppermessage = message

To prevent the code breaking when someone adds punctuation, special characters, or numbers, we’ll put the encryption and decoding function in a try-except block that will create a string out of whatever is throwing up an error, and insert it into the string that it sends back to us.

We use a simple ‘for’ statement in this bit of code, set to the length of the message the user typed in with Python’s handy range-length method, range(len()). That way, we don’t need to predict or restrict message lengths.  

printedmessage = ""
for x in range(len(uppermessage)):
  try:
    printedmessage += EncryptionKeybase.get(uppermessage[x], 0)
  except TypeError:
    tempstring = str(uppermessage[x])
    printedmessage += tempstring
return printedmessage

Let’s copy the code we wrote for the encryption function, and change it around so we can decode messages using our Decoder codebook. 

def decode_message(message):
 uppermessage = ""
 if message.isupper() != True:
   uppermessage = message.upper()
 elif message.isupper() == True:
   uppermessage = message
 printedmessage = ""
 for x in range(len(uppermessage)):
   try:
     printedmessage += DecoderKeybase.get(uppermessage[x], 0)
   except TypeError:
     tempstring = str(uppermessage[x])
     printedmessage += tempstring
 return printedmessage

There are ‘simpler’ ways to do this, for example you could use a loop inside of a loop to check each letter in the separate lists to return a result. However, that would be far less efficient. Always look at your code and think about how you could rewrite it to be shorter, simpler, and more efficient (that’s called refactoring). 

Step 4: Create the main program code that uses what you’ve written

Now that we have the main body of our code, let’s write the main program that will use our decoding and encryption functions. 

It would be irritating to have to restart the program every time you encrypt or decode one message, so let’s make the main body of our program work in a while loop that runs as long as we are sending messages. We can do this by using a boolean, which is a data type in Python which can be either ‘True’ or ‘False’. The program runs for as long our boolean value is set to ‘True’; as soon as ‘sending messages’ is changed to be = ‘False’, the program ends. 

sending_secret_messages = True
print("Welcome to the secret messaging app. Decode and encrypt your secret messages here!\n")
while sending_secret_messages:

Now that the program is running, let’s get the message we want to encrypt or decode from the user.

  message = input('\nType in the message you would like to be encrypted or decoded: ')

Let’s ask the user if they want to encrypt or decode this message. We’ll store their answer as a string, and then use an ‘if’ statement to determine which of our functions – decode or encrypt – to call. 

  encrypt_or_decode = input('\nWould you like to ENCRYPT or DECODE the message? [E/D]: ')

Now let’s make that ‘if’ statement. I’ve written in a version that checks both the uppercase and lowercase versions of their answer – you wouldn’t want to have a program fail just because you didn’t press caps lock!

This first piece of code will encrypt the user’s inputted message:

 if encrypt_or_decode == "E" or encrypt_or_decode == "e":
   print("\nYour encrypted message is:")
   encrypted_message = encrypt_message(message)
   print(encrypted_message)

And the second ‘elif’ statement will decode it:

 elif encrypt_or_decode == "D" or encrypt_or_decode == "d":
   print("\nYour decoded message is:")
   decoded_message = decode_message(message)
   print(decoded_message)

We also have to make sure we’re taking into account a possible situation where the user types in something we didn’t expect. This last ‘else’ statement will print a message asking them to type in the correct command, and just re-run the code. 

else: 
  print("Enter 'E' or 'D' to Encrypt or Decode a message.")
  continue

Finally, we can ask the user if they’d like to exit the secret coding app after every message. If they don’t want to keep sending messages, our boolean ‘sending secret messages’ is set to false, breaking the while loop and ending our program. 

 keep_sending_messages = input('\nWould you like to decode/encrypt another message? Y/N: ')
 if keep_sending_messages == 'n':
   sending_secret_messages = False

That’s it! You now have a program that converts messages using Python’s dictionaries. Give it a run, and test it out on this message written below:

QSWIOHAVMIX HK KATJQIOV DFOHBD’K PDOLIKJ JIBQ IMTBDJHAV WOAXHMIO. HJ UDK FATVMIM HV 2012, DK D KEDPP LODKKOAAJK EAXIEIVJ AF BAEWTJIO KBHIVBI KJTMIVJK UAORHVL JAUDOMK D KHVLPI LADP: JA NTHPM DVM MIPHXIO NIJJIO JIBQVHBDP IMTBDJHAV FAO DVSAVI UQA UDVJIM JA PIDOV MHLHJDP PHJIODBS DVM WOALODEEHVL KRHPPK.

Try writing out your own codebook, or encrypting your own message! Are there any other applications you think this program could be used for?

And remember that this is just beginner code written using what is taught in our free trials. You’ll learn much more complex and elegant solutions on the actual bootcamp – but it goes to show that with a bit of experimentation and the beginner essentials, you can make fun, useful, or just plain silly programs to keep you entertained. 

Our bootcamps take you from these beginner basics, and help you grow to be able to produce professional-grade code in just 3 to 6 months. We do this through specialised bootcamps that teach you real, practical skills in web development, software engineering, or data science. While you study online, or at our campuses in Joburg and Cape Town, you’ll receive 1-on-1 mentor support from a coding expert to ensure that the code you’re writing is of the standard tech recruiters are looking for. 

Sign up today for your free trial

 

Full copy of code:

https://repl.it/@wheresmattynow/SecretCoderNDecoder#main.py