Py学习  »  Python

为什么reverse(string[0:])在python中显示错误,为什么我不能使用它而不是reverse(string[1:])+string[0]

samiksha warang • 6 年前 • 1722 次点击  

请解释一下,我听不懂

def reverse(string):
        if len(string) == 0:
            return string
        else:
            return reverse(string[0:])
st = str(input("Enter the string to be reversed: "))
print(reverse(st))

以上代码给出的错误如下:

Enter the string to be reversed: samiksha
Traceback (most recent call last):
  File "C:\Users\samiksha warang\Desktop\python\lab exps\exp3.py", line 40, in <module>
    print(reverse(st))
  File "C:\Users\samiksha warang\Desktop\python\lab exps\exp3.py", line 38, in reverse
    return reverse(string[0:])
  File "C:\Users\samiksha warang\Desktop\python\lab exps\exp3.py", line 38, in reverse
    return reverse(string[0:])
  File "C:\Users\samiksha warang\Desktop\python\lab exps\exp3.py", line 38, in reverse
    return reverse(string[0:])
  [Previous line repeated 1021 more times]
  File "C:\Users\samiksha warang\Desktop\python\lab exps\exp3.py", line 35, in reverse
    if len(string) == 0:
RecursionError: maximum recursion depth exceeded while calling a Python object
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56443
文章 [ 1 ]  |  最新文章 6 年前