Python 如何判断一个整数是偶数还是奇数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14651025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:03:09 来源:igfitidea点击:
How to determine if an integer is even or odd
提问by user2033235
def is_odd(num):
# Return True or False, depending on if the input number is odd.
# Odd numbers are 1, 3, 5, 7, and so on.
# Even numbers are 0, 2, 4, 6, and so on.
I'm wondering what you would do from here to get those answers.
我想知道你会怎么做才能得到这些答案。
回答by NPE
def is_odd(num):
return num % 2 != 0
Symbol "%" is called modulo and returns the remainder of division of one number by another.
符号“%”称为模数,返回一个数除以另一个数的余数。
回答by unutbu
def is_odd(num):
return num & 0x1
It is not the most readable, but it is quick:
它不是最易读的,但它很快:
In [11]: %timeit is_odd(123443112344312)
10000000 loops, best of 3: 164 ns per loop
versus
相对
def is_odd2(num):
return num % 2 != 0
In [10]: %timeit is_odd2(123443112344312)
1000000 loops, best of 3: 267 ns per loop
Or, to make the return values the same as is_odd:
或者,使返回值与is_odd:
def is_odd3(num):
return num % 2
In [21]: %timeit is_odd3(123443112344312)
1000000 loops, best of 3: 205 ns per loop

