Search code examples
pythondictionarymorse-code

Allowing multiple characters in morse code converter


I'm making a program that takes input and coverts it to morse code in the form of computer beeps but I can't figure out how to make it so I can put more than one letter in the input without getting an error.

Here is my code:

import winsound
import time

morseDict = {
'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': '--..'
}
while True: 
    inp = raw_input("Message: ")
    a = morseDict[inp] 
    morseStr =  a
    for c in morseStr:
        print c
        if c == '-':
            winsound.Beep(800, 500)
        elif c == '.':
            winsound.Beep(800, 100)
        else:
            time.sleep(0.4)  
        time.sleep(0.2)

Right now it takes one letter at a time but I want it to take phrases.


Solution

  • just add an extra for loop and loop through the characters in your input to get the message! But don't forget to end your loop when necessary!

    In the following code I made it such that after the message has been decoded, it asks if you would like to send another, if you type "n" it will quit the loop!

    going = True
    while going: 
        inp = raw_input("Message: ")
        for i in inp:
            a = morseDict[i] 
            morseStr =  a
            for c in morseStr:
                print c
                if c == '-':
                    winsound.Beep(800, 500)
                elif c == '.':
                    winsound.Beep(800, 100)
                else:
                    time.sleep(0.4)  
                time.sleep(0.2)
        again = raw_input("would you like to send another message? (y)/(n) ")
        if again.lower() == "n":
             going = False
    

    now you still have one problem...you have not accounted for spaces!! So you can still only send words! If I am correct, a space between words is a fixed timed silence in morse code, so what I would say you should do is add:

    " ": 'x'
    

    this way it will not return an error when trying to find the instance of the space and it will run in your else statement and add an extra .4 seconds before the next word!