I create a code to test if the string is palindrome or not. The test pass exept when I give the function one character. at this time I got this error:
UnboundLocalError: local variable 'is_palindrome' referenced before assignment
"""
Given a string str, return true if the str can be palindrome and false if not.
Input: str = "aba"
Output: true
Input: str = "abc"
Output: false
"""
def validPalindrome(str: str) -> bool:
for i in range(len(str)//2):
is_palindrome = False
if str[i] == str[-i-1]:
is_palindrome = True
if is_palindrome:
return True
else:
return False
print(validPalindrome('aba'))
print(validPalindrome('abc'))
print(validPalindrome('a'))
CodePudding user response:
When you use if is_palindrome
in line 6 of your function, it should have been defined before. if your input is a single character, your input length is 1, and thus 1//2 = 0. program never enters the loop. and thus is_palindrome
is never defined. I think changing the program to this would help.
def validPalindrome(str: str) -> bool:
is_palindrome = True
for i in range(len(str)//2):
if str[i] != str[-i-1]:
is_palindrome = False
break
return is_palindrome
CodePudding user response:
You should set the is_palindrome
variable in the right scope:
def validPalindrome(str: str) -> bool:
is_palindrome = False
...