Reputation: 57
I'm trying to make a text-to-morse translator with Python (using Python 3.8 in vs code) But there's a problem in line running order. This is my code(question is after the code):
import winsound
import time
def beep(char):
sound = {
'-': 500,
'.': 150,
}
for dashdot in item_dict[char]:
winsound.Beep(500, sound[dashdot])
time.sleep(.05)
item_dict = {
'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': '----.',
'.': '.-.-.-',
',': '--..--',
'?': '..--..',
'-': '-...-',
'/': '-..-.'
}
def morse():
x = input("?\n")
name_list = list(x)
for x in name_list:
print(item_dict[f"{x}"], end=' ')
beep(x)
time.sleep(.5)
morse()
print('''text to morse-text
enter the text you want''')
morse()
as you can see in this part:
for x in name_list:
print(item_dict[f"{x}"], end=' ')
beep(x)
time.sleep(.5)
The element print
is before the function beep
. So it should first print and then make the noise. But it makes the noises and then, after making noise for all chars, prints the codes. What's wrong with it?
Upvotes: 3
Views: 113
Reputation: 1255
Add flush=True
to your print
statement like so:
print(item_dict[f"{x}"], end=' ', flush=True)
This forces the output on the console. This is useful in your case, when you specify a custom "end of the line" argument. When it's not a newline, it doesn't get automatically printed as is.
Upvotes: 3
Reputation: 1
Im not quite sure I understand your question fully, but your program currently first prints the morse value of a letter to the console, and next makes the corresponding sound. So if that is what you wanted, you don't have to change anything.
Otherwise if you want to print the morse for the whole sentence, and after that make all the corresponding sounds, you can just use two loops:
def morse():
x = input("?\n")
for char in x:
print(item_dict[char], end=' ')
for char in x:
beep(char)
time.sleep(.5)
morse()
instead of making a list of the string input like:
name_list = list(x)
for x in name_list:
you can just past the input string in the for loop, it will automatically loop over every character in your string:
for char in x:
where x
is your input string
Upvotes: -1