Dav*_*ang 5 python if-statement list
我对编程很新,我被分配了一个将英文文本转换为Pig Latin的家庭作业.
我到目前为止的代码是:
VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
def vowel_start(word):
pig_latin = word + "ay"
return pig_latin
def vowel_index(word):
for i, letters in enumerate(word):
if letters in VOWELS:
vowel_index = i
pig_latin = word[vowel_index:] + word[:vowel_index] + "ay"
return pig_latin
else:
pig_latin = word #The issue here is that even if the word
return pig_latin #has vowels, the program will still only
#return the untranslated word as shown
#in else.
english_text = raw_input("What do you want to translate?")
translate = english_text.split()
pig_latin_words = []
translated_text = "".join(str(pig_latin_words)) #The issue here is that the list
#will not join with the string.
for i in translate:
first = i[0]
vow = False
if first in VOWELS:
vow = True
if vow == True:
pig_latin_words.append(vowel_start(i))
else:
pig_latin_words.append(vowel_index(i))
print "The text you translated is " + english_text
print "The translated text is " + translated_text #The issue here is that the program
#displays "The translated text is "
#and that's it
Run Code Online (Sandbox Code Playgroud)
如果我注释掉def vowel_index函数的else方面,那么if方面就可以了.如果我把它留在程序中,if方面不再起作用.过去几天我一直试图解决这个问题,我不知道如何修复它.任何帮助将不胜感激,谢谢!
有关作业的更多详细信息:
你的函数当前的编写方式,你将始终返回for循环的第一次迭代,基于第一个字符是元音与否.如果没有字符是元音,则需要遍历每个字符并仅返回单词不变.
首先删除else; 当你看到一个不是元音的单个字符时,你不想返回,因为后面的字符可能是一个元音.现在既然你有一个return声明if,你知道如果你到达循环的末尾而没有返回没有任何字符word是元音,那么你可以在for循环之外返回单词.例如:
def vowel_index(word):
for i, letters in enumerate(word):
if letters in VOWELS:
vowel_index = i
return word[vowel_index:] + word[:vowel_index] + "ay"
return word
Run Code Online (Sandbox Code Playgroud)
对于你的第二个问题,这里有几件事情.
首先,你需要移动创建,translated_text以便它pig_latin_words已经有了新单词.这将在你最后的印刷陈述之前.
此外,要将单词列表转换为由空格分隔的单个字符串,您应该使用以下内容:
translated_text = " ".join(pig_latin_words)
Run Code Online (Sandbox Code Playgroud)
这是一个显示差异的简短示例:
>>> pig_latin_words = ['atcay', 'ogday']
>>> print "".join(str(pig_latin_words)) # your version
['atcay', 'ogday']
>>> print " ".join(pig_latin_words) # my version
atcay ogday
Run Code Online (Sandbox Code Playgroud)