我正在尝试制作一个程序来检查单词是否是回文,并且到目前为止,它可以与具有偶数个数字的单词一起使用。我知道如果字母的数量为奇数时如何使它起作用,但是我只是不知道如何确定数字是否为奇数。有什么简单的方法可以找到数字是奇数还是偶数?
仅供参考,这是我的代码:
a = 0 while a == 0: print("\n \n" * 100) print("Please enter a word to check if it is a palindrome: ") word = input("?: ") wordLength = int(len(word)) finalWordLength = int(wordLength / 2) firstHalf = word[:finalWordLength] secondHalf = word[finalWordLength + 1:] secondHalf = secondHalf[::-1] print(firstHalf) print(secondHalf) if firstHalf == secondHalf: print("This is a palindrom") else: print("This is not a palindrom") print("Press enter to restart") input()
谢谢
if num % 2 == 0: pass # Even else: pass # Odd
该%符号就像除法一样,仅检查余数,因此除以数字2的余数0甚至是奇数。
%
2
0
或者反转它们以提高速度,因为任何大于0的数字也被视为“ True”,因此您可以跳过进行任何相等性检查的步骤:
if num % 2: pass # Odd else: pass # Even