-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!'
顯然最後「她說」重複了,我不想發生。我怎樣才能解決這個問題?
編輯:我忘了提文本與「她說‘你好!’」
您的打印多了一個「她說,」在代碼中的最後一次打印,無論輸入什麼 – galfisher
我知道,問題是,代碼生成的文本始終以「他說,」而我要開始改變輸入是奇數還是偶數。 – Vectrex28
在這種情況下,當你點擊1而不是0時結束,並使用原始打印語句 – galfisher