在 Python 中检查数字是奇数还是偶数

我正在尝试编写一个程序来检查一个单词是否是回文,到目前为止我已经得到了,它工作的单词有一个偶数的数字。我知道如何让它做一些事情,如果字母的数量是奇数,但我只是不知道如何找出一个数字是奇数。有没有什么简单的方法来确定一个数字是奇数还是偶数?

作为参考,这是我的代码:

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()
357302 次浏览

One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.

Hope it helps,

if num % 2 == 0:
pass # Even
else:
pass # Odd

The % sign is like division only it checks for the remainder, so if the number divided by 2 has a remainder of 0 it's even otherwise odd.

Or reverse them for a little speed improvement, since any number above 0 is also considered "True" you can skip needing to do any equality check:

if num % 2:
pass # Odd
else:
pass # Even

The middle letter of an odd-length word is irrelevant in determining whether the word is a palindrome. Just ignore it.

Hint: all you need is a slight tweak to the following line to make this work for all word lengths:

secondHalf = word[finalWordLength + 1:]

P.S. If you insist on handling the two cases separately, if len(word) % 2: ... would tell you that the word has an odd number of characters.

It shouldn't matter if the word has an even or odd amount fo letters:

def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False

Use the modulo operator:

if wordLength % 2 == 0:
print "wordLength is even"
else:
print "wordLength is odd"

For your problem, the simplest is to check if the word is equal to its reversed brother. You can do that with word[::-1], which create the list from word by taking every character from the end to the start:

def is_palindrome(word):
return word == word[::-1]

Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:

if x & 1:
return 'odd'
else:
return 'even'

Using Bitwise AND operator

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.