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.
Try changing your loop to something like this:
while True:
inp = raw_input("Message: ")
for char in inp:
for x in morseDict[char]:
print x
if x == "-":
winsound.Beep(800, 500)
elif x == ".":
winsound.Beep(800, 100)
else:
time.sleep(0.4)
time.sleep(0.2)
That way you iterate first over the characters in the input, then you look up the character in morseDict
and iterate over the value of morseDict[char]
.
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!
I believe you need to iterate over the letters in input.
while True:
inp = raw_input("Message: ")
for letter in inp: # <- Edit in this line
a = morseDict[letter] # <- and this one, rest have increased indent
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)
time.sleep(0.4) # Or desired time between letters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With