我已经被困在一个问题上一段时间了:
我正在寻找创建一个使用字符串和正整数的 python 函数。该函数将打印字符串 n 次,共 n 行。我 不能 使用循环,我只能使用递归
例如
>>> repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
每当我尝试创建一个执行此操作的函数时,该函数都会逐渐减少字符串的长度:
例如
>>> repeat("hello", 3)
hellohellohello
hellohello
hello
这是我的代码的样子:
def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
这种尝试有什么问题?我该如何解决?
原文由 Andrew Louis 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试这个