Python教程

Python | 浅学 | 7 NameError: name 'cmp' is not defined | AttributeError: module 'oper

本文主要是介绍Python | 浅学 | 7 NameError: name 'cmp' is not defined | AttributeError: module 'oper,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

NameError: name 'cmp' is not defined
**报错原因:**因为python3.x中cmp函数去掉了,如果需要实现比较功能,那么可引入operator 模块,提供了6个比较运算符。gt lt ge eq le 

import operator             #首先要导入运算符模块operator
# integers
x,y = 100,200
print("x:",x, ", y:",y)
print("operator.gt(x,y):", operator.gt(x,y)) #大于  False
print("operator.gt(y,x):", operator.gt(y,x)) #大于  True
# strings
x,y  = "A","B"
print("x:",x, ", y:",y)
print("operator.gt(x,y):", operator.gt(x,y)) #大于  False
print("operator.gt(y,x):", operator.gt(y,x)) #大于  True
# list
list1, list2 = [1235, 'xyz'], [456, 'abc']
print("operator.gt(list1,list2):", operator.gt(list1,list2)) #大于  True
print("operator.gt(list2,list1):", operator.gt(list2,list1)) #大于  False
# printing the return type of the function
print("type((operator.gt(x,y)):", type(operator.gt(x,y)))
print(operator.lt(x,y))  #小于
print(operator.ge(x,y))  #大于等于
print(operator.eq(x,y))  #等于
print(operator.le(x,y))  #小于等于

 

这篇关于Python | 浅学 | 7 NameError: name 'cmp' is not defined | AttributeError: module 'oper的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!