Morse code looks old-fashioned, yet it is a brilliant first encoding system for any programmer. It turns letters into a small alphabet of dots, dashes and gaps — in other words, a binary-like code that predates modern computing by more than a century.
Why programmers should care
Every character becomes a short sequence. A is .-, B is -..., and SOS is the famous ... --- .... That is exactly what encoding means: a rule that maps one representation to another, reversibly and without ambiguity. If you can build a Morse encoder, you understand dictionaries, lookup tables, string parsing and edge cases.
Try it live with a free Morse Code Translator — type a sentence, watch it become dots and dashes, then decode it back again. It is a handy way to check your own encoder against a known result.
The alphabet, in code
Start with the Morse code alphabet as your lookup table. In Python, the core is a dictionary:
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': '--..',
'1': '.----', '2': '..---', '3': '...--',
'4': '....-', '5': '.....', '6': '-....',
'7': '--...', '8': '---..', '9': '----.',
'0': '-----',
}
def encode(text):
words = text.upper().split(' ')
return ' / '.join(
' '.join(MORSE.get(ch, '') for ch in word)
for word in words
)
print(encode('Hello World'))
# .... . .-.. .-.. --- / .-- --- .-. .-.. -..
Timing is part of the protocol
Morse is not only symbols; it is timing. A dash lasts three dot-lengths, the gap between letters is three units, and the gap between words is seven. Get the timing wrong and a decoder will misread you, just as a parser fails on malformed input. When you build a decoder, split on word gaps first, then letter gaps, then look each symbol up in reverse.
Three small projects to try
- Encoder and decoder: build both directions and round-trip test them with random words.
- Sound player: use the Web Audio API or a simple beeper to play dots and dashes at different speeds.
- Translator UI: add a copy button, a speed slider and a light that flashes as the code plays.
Common pitfalls
- Forgetting to handle unknown characters — skip them, or raise a clear error.
- Mixing up letter and word separators; use a single space between letters and
/between words. - Hard-coding only A–Z and then failing on digits and punctuation.
- Assuming decoding is unique without separators; without gaps,
...could beSorEEE.
Morse code is a compact, practical lesson in encoding, and it still works today — in amateur radio, in puzzles, in accessibility tools and in teaching. Build your own encoder, test it against the free online Morse code translator at Morse Zone, and you will have learned more about data representation than most tutorials teach in a week.
Top comments (0)