problem with the recursive method and the global variable in python 3

advertisements

Here is the code:

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)

I am getting errors at the three nums, which say: unresolved reference 'num', and I am getting the error local variable 'num' referenced before assignment when I run it. But I defined num before the method, so why am I getting these errors? thanks

edit: answered it myself


In python, to keep track of variables that need to exist during the recursion, you use an argument with a default value.

def palindromeMethod(theWord, num=0):
                       # here ^
    length = len(theWord)
    if(theWord[num]==theWord[length-num-1]):
        if(num>=length-1):
            return True
        return palindromeMethod(theWord, num+1)
                          # pass it here ^
    else:
        return False

if palindromeMethod('aabbccbbaa'):
   # don't need to pass it here ^
    print('its a palindrome')

I moved the print outside the function and fixed some off-by-one errors.