Morse Code Translator

Simple both way converting script

Posted by Kossanovic on February 26, 2023

Received a suspicious message?

Fear no more, this fancy thing is here for help. If you just happen to see or hear a lot of long - short signals it may actually mean something. If you want to find out what, just use this and answer back!

Okay, so first thing is to get a translation code, we will use Python dictionary to do so. Key is letter from our alphabet, value is Morse Code:
 

international_morse_code = {
    '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': '--..',

    '0': '-----', '1': '.----', '2': '..---',
    '3': '...--', '4': '....-', '5': '.....',
    '6': '-....', '7': '--...', '8': '---..',
    '9': '----.', " ": "/"
}

The "convert_message" function is responsible for converting a message to Morse code or vice versa. If the input message starts with a dot or a dash, the function assumes that it is a Morse code message and converts it to the corresponding alphanumeric message. On the other hand, if the input message is an alphanumeric message, the function converts it to the corresponding Morse code message. The function handles input errors by catching the KeyError exception when the input contains invalid characters that are not present in the Morse code dictionary.

def convert_message(message_to_convert):
    if message_to_convert[0] in [".", "-"]:
        swap_code = {v: k for k, v in international_morse_code.items()}
        return "".join(swap_code[symbol] for symbol in message_to_convert.split(" "))
    return " ".join(international_morse_code[letter.capitalize()] for letter in message_to_convert)

The "convert_again" function is a loop that allows the user to convert multiple messages. It prompts the user to enter a message and calls the "convert_message" function to convert the message to its Morse code or alphanumeric representation. After conversion, it prompts the user to enter whether they want to convert another message. If the user inputs "yes," the function loops again. If the user inputs "no," the function breaks out of the loop and the program ends.

def convert_again():
    while True:
        message = input("Type your message to convert: ")
        try:
            print(convert_message(message))
            answer = input("Do you want to convert again? Type yes or no: ").lower()
            if answer == "yes":
                convert_again()
            else:
                break
        except KeyError:
            print("Looks like there was an invalid input.")
            continue
        else:
            break

Then we just call it, and voila.

convert_again()