Python 索引器错误:字符串索引超出范围3
此代码基本上是镜像您输入的字符串。我越来越Python 索引器错误:字符串索引超出范围3,python,string,recursion,indexing,index-error,Python,String,Recursion,Indexing,Index Error,此代码基本上是镜像您输入的字符串。我越来越 Type something please: Hey Hello Traceback (most recent call last):
Type something please: Hey Hello
Traceback (most recent call last):
File "Week3Basic1.py", line 13, in <module>
mirror(input("Type something please: "))
File "Week3Basic1.py", line 9, in mirror
result = last+ mirror(middle) + first
File "Week3Basic1.py", line 9, in mirror
result = last+ mirror(middle) + first
File "Week3Basic1.py", line 9, in mirror
result = last+ mirror(middle) + first
File "Week3Basic1.py", line 4, in mirror
first= string[0]
IndexError: string index out of range
为了正确工作,函数假定输入长度至少为两个字符
同时,它在输入的缩写版本上递归地调用它自己——需要考虑递归调用的链何时以及如何停止。
您需要考虑的这一方面称为。您的类应该提到递归中的基本情况。想想你的基本情况。
def mirror(string):
first= string[0]
middle= string[1:-2]
last= string[-1]
result = last+ mirror(middle) + first
print (result)
mirror(input("Type something please: "))