我正在尝试扩展Codeacademy的Pig Latin转换器以实践基本的编程概念。
我相信我的逻辑几乎是正确的(我确信它不是那么简洁!)现在我试图输出用户在一行输入的转换后的Pig拉丁语句子。
如果我从for循环内部打印,则每次都会在新行上打印。如果我从外面打印它只打印第一个单词,因为它没有遍历所有单词。
你能告诉我哪里出错吗?
很多,非常感谢你的帮助。
pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
print "You entered \"%s\"." % original
split_list = original.split()
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = "".join(new_sentence)
print final_sentence
break
else:
print ("That's not a valid input. Please try again.")
return convert(raw_input("Please enter a word: "))
convert(raw_input("Please enter a word: "))
答案 0 :(得分:0)
尝试:
pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
final_sentence = ""
print "You entered \"%s\"." % original
split_list = original.split()
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = final_sentence.append(new_sentence)
print final_sentence
break
else:
print ("That's not a valid input. Please try again.")
return convert(raw_input("Please enter a word: "))
convert(raw_input("Please enter a word: "))
这是因为你每次都在for循环中重建final_sentence而不是添加它。
答案 1 :(得分:0)
我不确定程序逻辑,但快速解决方案是将所有final_sentence附加到列表中,并在打印后使用Join打印列表。
pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
to_print = []
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
print "You entered \"%s\"." % original
split_list = original.split()
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = "".join(new_sentence)
to_print.append(final_sentence)
print " ".join(to_print)
break
else:
print ("That's not a valid input. Please try again.")
return convert(raw_input("Please enter a word: "))
convert(raw_input("Please enter a word: "))
此代码可以满足您的需求吗?
答案 2 :(得分:0)
您的问题在这里:
final = []
for word in split_list:
new_word = word[1:] + word[0] + pyg
final.append(new_word)
print ' '.join(final)
你正在为自己加入一个单词。您需要保存循环内的所有单词,然后在循环处理完所有内容后打印它们。
print ' '.join([word[1:]+word[0]+'ay' for word in split_list])
或者,只是为了好玩,这里是单行:
,
编辑: 此外,@ furas在评论中提出了一个很好的观点,使用无换行进行打印只需添加{{1}到打印语句的末尾:
for word in split_list:
first = word[0]
print word[1:] + first + pyg,