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?
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.