的cmp()是,其比较两个整数Python标准库的一部分。如果第一个整数小于第二个,则比较结果为-1,如果第一个整数大于第二个,则比较结果为1。如果两者相等,则结果cmp()为零。
下面的示例说明了显示cmp()方法使用情况的不同场景。
示例def cmp(x, y):
return (x > y) - (x
#x>y
x = 5
y = 3
print("The cmp value for x>y is : ",cmp(x, y),"\n")
#x
x = 7
y = 9
print("The cmp value for x
#x=y
x = 13
y = 13
print("The cmp value for x=y is : ",cmp(x, y))
#odd and even
k = 16
if cmp(0, k % 2):
print("\n","The given number",k,"is odd number ")
else:
print("\n","The given number",k,"is even number")
k= 31
if cmp(0, k % 2):
print("\n","The given number",k,"is odd number")
else:
print("\n","The given number",k,"is even number")
输出结果
运行上面的代码给我们以下结果-The cmp value for x>y is : 1
The cmp value for x
The cmp value for x=y is : 0
The given number 16 is even number
The given number 31 is odd number