2017-05-08 62 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)