在python中检查数字是奇数还是偶数 [英] Check if a number is odd or even in python

查看:72
本文介绍了在python中检查数字是奇数还是偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a program which checks if a word is a palindrome and I've gotten so far and it works with words that have an even amount of numbers. I know how to make it do something if the amount of letters is odd but I just don't know how to find out if a number is odd. Is there any simple way to find if a number is odd or even?

仅供参考,这是我的代码:

Just for reference, this is my code:

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否则很奇怪.

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.

或者将它们反转以提高一点速度,因为任何大于 0 的数字也被视为真",您可以跳过需要进行任何相等性检查:

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 

这篇关于在python中检查数字是奇数还是偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆