2017-04-24 76 views
1

我遇到了代码只生成第一个单词的前两个字母,然后在运行时将'AY'附加到结尾的问题。我似乎无法弄清楚如何纠正这个错误。python的输出代码pig latin问题

def main(): 
     strin = input('Enter a sentence (English): ') 
     strlist = strin.split() 
     i = 0 
     pigsen = '' 
     while i < len(strlist): 
      word = strlist[i] 
      j = 1 
      fc = word[0].upper() 
      pigword ='' 
      while j < len(word): 
       pigword += word[j].upper() 
       j += 1 
       pigword += fc + 'AY' 
       pigsen += pigword + ' ' 
       i +=1 
     print('Pig Latin: ' +str(pigsen)) 
main() 
+0

了解如何使用Python源代码调试器并逐步完成代码。错误将更容易找到。 –

回答

0

首先,我会认为这是一个猪拉丁产生的仅仅是开始,一旦你获得这么多的工作,你会添加其他规则(至少一对夫妇更多)。其次,让我们简化代码修复它的一种方式:

def main(): 
    sentence = input('Enter a sentence (English): ') 

    words = sentence.upper().split() 

    latin_words = [] 

    for word in words: 

     first, rest = word[0], word[1:] 

     latin_word = rest + first + 'AY' 

     latin_words.append(latin_word) 

    print('Pig Latin:', *latin_words) 

main() 

用法

> python3 test.py 
Enter a sentence (English): He complimented me on my English 
Pig Latin: EHAY OMPLIMENTEDCAY EMAY NOAY YMAY NGLISHEAY 
> 

我要说你的代码的问题是,你做它太复杂了。