So this code has worked correctly without the try clause, but I need it to work in this manner because I want to continue prompting the user for input and give an option to exit. Ive searched and cant find a similar questions asked. Can someone please take a look and see what Im missing, thanks.
vowels = 'aeiou'
def converter(word):
while True:
try:
first = word[0]
if first in vowels:
word = word + 'yay'
return word
else:
while word[0] not in vowels:
word = word[1:] + word[0]
word = word + 'ay'
return word
split = word.split()
translated = [converter(word) for word in split]
translated = " ".join(translated)
print(translated)
except ValueError:
if word.lower() == "exit":
word = word.lower()
print("Adios")
else:
print("Try again.\n")
converter(input('Words to translate into piglatin: '))
1 Answer 1
The problem with the code is that it enters an infinite while loop in the converter() function.
You should move the while loop outside the function:
while True:
converter(input('Words to translate into piglatin: '))
Then, you can process the input to check if the user wants to quit. If the user chooses not to quit, then you should pass the input string to the converter() function. You already have most of the components needed looking at your CodeHS link without the try/except block.
print(<variable>)toreturn <variable>in order to return values for pythonprintandreturnhave nothing to do with each other.