输出应该像这个Hip Hurray!
def cheers(n):
if n == 0:
print("Hurray!!!")
elif n == 1:
print('Hip' + ' ' + 'Hurray!!!')
elif n > 1:
cheers(n-1)
print('Hip' + "Hurray!!!")
cheers(3)发布于 2022-02-22 11:16:09
def hip_hip_hurray(n, message):
if n == 0:
print(message + 'Hurray!')
else:
hip_hip_hurray(n - 1, message + 'Hip ')
hip_hip_hurray(3, '')
# prints: Hip Hip Hip Hurray!这里的诀窍是使用message参数作为最终输出的聚合器,使用停止条件添加Hurray后缀并打印消息。
发布于 2022-02-22 11:19:47
如果您想要的是递归解决方案,只需这样做.很管用!!
def cheers(n):
if n<=0:
print("Hurray!!!")
return
print("Hip",end=" ")
cheers(n-1)发布于 2022-02-22 11:15:37
你就不能这么做吗?
def cheers(n):
print('Hip ' * n + 'Hurray!!!')
cheers(3) # Hip Hip Hip Hurray!!!使用递归:
def cheers(n):
if n == 0:
return 'Hurray!!!'
return "Hip " + cheers(n - 1)
print(cheers(3))
# Hip Hip Hip Hurray!!!https://stackoverflow.com/questions/71220267
复制相似问题