Py学习  »  Python

使用python时字符串是否为回文-UnboundLocalError

Aykc • 3 年前 • 1188 次点击  

我创建了一个代码来测试字符串是否是回文。当我给函数一个字符时,测试通过。这时我发现了一个错误:

UnboundLocalError:赋值前引用了局部变量“is_palindrome”

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130636
 
1188 次点击  
文章 [ 2 ]  |  最新文章 3 年前