We add a new function called encode
which takes the exact code as before but with three changes:
def encode(message):
added to the beginningreturn morse_message
added to the endWe then call our function with morse_message = encode(message)
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_message
morse_message = encode(message)
print(f"Incoming message: {message}")
print(f" Morse encoded: {morse_message}")
python encode.py