-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