2017-05-08 50 views
-2

我正在做一些Python递归循环练习,我有一个小问题,我的程序Python的递归循环愁楚

def buildSentence(timesSay,saySentence): 
    if timesSay != 0: 
     timesSay -= 1 
     if (timesSay % 2 == 0): 
      saySentence = "he said that " + saySentence 
     else: 
      saySentence = "she said that " + saySentence 
     return buildSentence(timesSay,saySentence) 
    else: 
     return (saySentence) 


try: 
    timesSayInput = int (input("Please enter a number... ")) 
except ValueError: 
    print ("This is not a number!!!") 

print (buildSentence(timesSayInput,"she said 'Hello!'")) 

之一的代码应该以“她说,”交替输出文本和“他说过”。当我输入3(或任何奇数),代码工作,因为它应该和输出

he said that she said that he said that she said 'Hello!' 

然而,当我输入2(或任何偶数),其输出

he said that she said that she said 'Hello!' 

显然最后“她说”重复了,我不想发生。我怎样才能解决这个问题?

编辑:我忘了提文本与“她说‘你好!’”

+2

您的打印多了一个“她说,”在代码中的最后一次打印,无论输入什么 – galfisher

+0

我知道,问题是,代码生成的文本始终以“他说,”而我要开始改变输入是奇数还是偶数。 – Vectrex28

+0

在这种情况下,当你点击1而不是0时结束,并使用原始打印语句 – galfisher

回答

0

分析

看看你的输出来结束:无论输入的号码,你总是以“他说”。你正在用错误的顺序撰写你的句子:你必须结尾与“他说”,而不是带领它。这就是为什么你的一半结果是错误的。

REPAIR

更改操作的顺序,使得最后一句话你添加(当timesSay == 1)是最接近这句话,不是最远的。代码如下。

def buildSentence(timesSay,saySentence): 
    if timesSay > 0: 
     if timesSay % 2: 
      return "he said that " + buildSentence(timesSay-1, saySentence) 
     else: 
      return "she said that " + buildSentence(timesSay-1, saySentence) 
    else: 
     return (saySentence)