can anyone help me out with this its a morse code progam and I want the user to input either t or m; t for text and m for morse code everytime I run it no matter if I input t it always says enter morse code to translate instead of enter text to translate, id appreciate any help!
while True:
print("")
Input = input("My input is: ")
message=input("Enter morse code to translate: ")
encodedMessage = ""
if Input.startswith ("m"):
for word in message.split(" "):
for char in word.split():
if char in morse:
encodedMessage+=morse[char] + " "
print("Your translation to text is: ",encodedMessage)
else:
print("Value for %r not found as morse."%char)
if Input.startswith ("t"):
print("Enter text to translate: ")
decodedMessage = ""
for word in hello.split():
if char in morseCode:
decodedMessage+=morseCode[char] + " "
print("Your translation to morse is: ",decodedMessage)
else:
print("Value for %r not found as a character."%char)
2 Answers 2
You had your second if statement for Input starting with t way too far indented such that it would only execute if the input started with "m" (and thus fail). Next, you had the input asking for morse code outside your if statements (so it'd always get shown, not after you verified what you were looking for). I've changed it to be closer to what I think you wanted:
while True:
print("")
Input = input("My input is: ")
if Input.startswith ("m"):
message=input("Enter morse code to translate: ")
encodedMessage = ""
for word in message.split(" "):
for char in word.split():
if char in morse:
encodedMessage+=morse[char] + " "
else:
print("Value for %r not found as morse."%char)
print("Your translation to text is: ",encodedMessage)
elif Input.startswith ("t"):
hello = input("Enter text to translate: ")
decodedMessage = ""
for word in hello.split():
for char in word:
if char in morseCode:
decodedMessage+=morseCode[char] + " "
else:
print("Value for %r not found as a character."%char)
print("Your translation to morse is: ",decodedMessage)
I've also moved your final print lines outside of your for loops as you probably wouldn't want to slowly print out the encoded/decoded message at each character, but just the end result. I also added a for loop in the case you're looking at text to loop through each character in the word.
Comments
use == for comparison instead of startswith.
change
if Input.startswith ("m"):
to
if Input == "m":
Input, capitali, is an available variable name. It's not very descriptive, but it doesn't mask anything.