如果数字是回文,则编写函数来处理

时间:2013-10-25 01:36:53

标签: python function reverse

所以我使用2种不同的函数来评估输入的数字是否是回文数。但似乎无论我做什么我的结果总是“数字不是一个palinrome”即使数字实际上是。这是我的代码,应该很容易,但它只是不起作用。

def reverse(number):
    return (int(str(number)[::-1]))
def isPalindrome(number):
    reverse(number)
    if number == reverse(number):
        return True
    else:
        return False
def main():
    num = (input("Enter a number: "))
    if isPalindrome(num) == True:
        print("The number is a Palindrome")
    elif isPalindrome(num) == False:
        print("The number is not a Palindrome")
main()

1 个答案:

答案 0 :(得分:2)

isPalindrome(number)中,数字是字符串,但是reverse(number)返回int

所以number == reverse(number)总是False(字符串!= int)

更改reverse()

def reverse(number):
    return number[::-1]

def isPalindrome(number):
    #print(type(number))
    #print(type(reverse(number)))
    return number == reverse(number)

def main():
    num = input("Enter a number: ")

    if isPalindrome(num) == True:
        print("The number is a Palindrome")
    else:
        print("The number is not a Palindrome")

main()

或使用num = int(input("Enter a number: "))

def reverse(number):
    return int(str(number)[::-1])

def isPalindrome(number):
    #print(type(number))
    #print(type(reverse(number)))

    return number == reverse(number)

def main():
    num = int(input("Enter a number: "))

    if isPalindrome(num) == True:
        print("The number is a Palindrome")
    else:
        print("The number is not a Palindrome")

main()