代码如下:
aWord = input("enter the word now")
num = 0
def palindromeMethod(theWord):
length = len(theWord)
if(theWord[num]==theWord[length-num]):
if(num>length):
print("its a palindrome")
num = num+1
palindromeMethod(theWord)
else:
return False
palindromeMethod(aWord)
我在三个num
处得到错误,它们说:unresolved reference 'num'
,我在运行它时得到错误local variable 'num' referenced before assignment
。但是我在方法之前定义了num
,那么为什么我会得到这些错误呢?谢谢
编辑:我自己回答的
不需要索引或长度
但你可能被要求使用它们。。。在
编辑
下面是一个评论,这有效地缩小了可能的反应范围,这里是一个看马,没有切片的版本以上。在
^{pr2}$print
表达式用于显示函数的正在进行的工作,OP可能希望删除它们,因为它们没有被请求(NB:w/oprint
s等等,它是5个LOC)。在测试输出
最后的烟火:期待已久的一班
在python中,为了跟踪递归过程中需要存在的变量,可以使用带有默认值的参数。在
我将
print
移到函数之外,并修复了一些错误。在函数中的变量有一个局部作用域,因此需要在函数中初始化
num
!但是由于这里有一个递归函数,所以不能在函数中指定num=0
。在所以我对这个问题的建议是:
相关问题 更多 >
编程相关推荐