Python Palindrome试用和不打印

时间:2013-11-27 05:22:22

标签: python

len(line.strip()) == d获得None时,我的其他内容无法打印。

def isPalindrome(word):
    if len(word) < 1:
        return True
    else:
        if word[0] == word[-1]:
            return isPalindrome(word[1:-1])
        else:
            return False

def fileInput(filename):
    palindromes = False
    fh = open(filename, "r")
    length = input("Enter length of palindromes:")
    d = int(length)
    try:
        for line in fh:
            for s in str(len(line)):
                if isPalindrome(line.strip()):
                    palindromes = True
                    if (len(line.strip()) == d):
                        print(line.strip())
    except:
        print("No palindromes found for length entered.")
    finally:
        fh.close()

1 个答案:

答案 0 :(得分:2)

您的代码失败了,因为您的异常并不是输入文件中不存在d长度回文的唯一地方。 您还需要检查palindromes的值。

因此,在您的try-block结束时,添加一行打印"no palindromes found",如下所示:

def fileInput(filename):
  palindromes = False
  # more code
  try:
    # more code
    if not palindromes:
      print("No palindromes found for length entered.")
  except:
    print("No palindromes found for length entered.")
  finally:
    # more code

顺便说一下,我会按照以下方式清理你的功能:

def isPalindrome(word):
  if not len(word):  # is the same as len(word) == 0
    return True
  elif word[0] == word[-1]:  # no need for overly nested if-else-blocks
    return isPalindrome(word[1:-1])
  else:
    return False

def fileInput(filename):
  palindromes = False
  d = int(input("Enter length of palindromes:"))
  with open(filename) as fh:  # defaults to "r" mode. Also, takes care of closing the file for you
    for line in fh:
      word = line.strip()
      if isPalindrome(word) and len(word) == d:  # note that you didn't have the len(word)==d check before. Without that, you don't check for the length of the palindrome
        palindromes = True
        print(word)
    if not palindromes:
      print("No palindromes found for length entered.")