We add a new function called encode which takes the exact code as before but with three changes: 1. def encode(message): added to the beginning 2. The code is indented by four spaces 3. return morse_message added to the end
We then call our function with morse_message = encode(message)
encode.py
letter_to_morse = {'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':'----.',' ':'/'}message ="SOS We have hit an iceberg and need help quickly"def encode(message): morse = []for letter in message: letter = letter.lower() morse_letter = letter_to_morse[letter] morse.append(morse_letter) morse_message =" ".join(morse)return morse_messagemorse_message = encode(message)print(f"Incoming message: {message}")print(f" Morse encoded: {morse_message}")
Terminal/Command Prompt
python encode.py
Incoming message: SOS We have hit an iceberg and need help quickly
Morse encoded: ... --- ... / .-- . / .... .- ...- . / .... .. - / .- -. / .. -.-. . -... . .-. --. / .- -. -.. / -. . . -.. / .... . .-.. .--. / --.- ..- .. -.-. -.- .-.. -.--