Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

string is palindrome or not with python – UnboundLocalError

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'))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading