Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 为什么这段python代码在检查回文编号时显示错误。?_Python 3.x - Fatal编程技术网

Python 3.x 为什么这段python代码在检查回文编号时显示错误。?

Python 3.x 为什么这段python代码在检查回文编号时显示错误。?,python-3.x,Python 3.x,每当我运行is_palindrome('otto'),它都会显示错误“IndexError:string index out out range”…但是,当我刚刚编译代码时,它不会显示任何错误。谢谢你的帮助 def middle(word): return word[1:-1] def is_palindrome(word): if word[0] != word[-1]: return False elif len(word)<=1: return

每当我运行is_palindrome('otto'),它都会显示错误“IndexError:string index out out range”…但是,当我刚刚编译代码时,它不会显示任何错误。谢谢你的帮助

def middle(word):    
   return word[1:-1]

def is_palindrome(word):
  if word[0] != word[-1]:
    return False
  elif len(word)<=1:
    return True
  else:    
    return is_palindrome(middle(word))
def middle(单词):
返回字[1:-1]
def是_回文(单词):
如果单词[0]!=单词[-1]:
返回错误

elif len(word)现在发生的是,对于偶数个字符的字符串,它最终将运行回文(“”),这会抛出一个越界错误。尝试切换
len(word)请添加错误文本和堆栈跟踪(如果适用)。阅读有关调试代码的提示。编码器:您应该编辑您的问题并将其添加到其中。谢谢Phonzi..它现在可以工作..但是您能详细解释您对越界错误的观点吗..感谢您的帮助..谢谢@编码器当然,有很多资源可以更好地解释它,但一般来说,您可以将越界错误视为试图调用不存在的列表或字符串的一部分。例如,如果要调用仅包含1个字符的字符串的第三个字符,则会出现越界异常。在本例中,您的代码最初会尝试通过空字符串的倒数第二个字符来查找第二个字符。因此,这些字符不存在,您得到了一个异常。同样,有很多资源可以更好地解释这一点