ITPub博客

首页 > 应用开发 > Python > Python-unsupported operand type(s) for %: 'builtin_function_or_method' and 'int'

Python-unsupported operand type(s) for %: 'builtin_function_or_method' and 'int'

原创 Python 作者:dakulaDL 时间:2020-03-23 14:20:54 0 删除 编辑
numbers = [ 12 , 37 , 5 , 42 , 8 , 6 , 7 , 39 , 72 , 68 ]
even = []
odd = []
while   len (numbers) >  0  : 
      number = numbers.pop
       if (number %  2  ==  0 ):
          even.append(number)
       else :
          odd.append(number)
print ( '单数有:' ,odd)
print ( '双数有:' ,even)

今天在python 3中测试上面的代码,报错    if(number % 2 == 0):
TypeError: unsupported operand type(s) for %: 'builtin_function_or_method' and 'int'

开始考虑可能number是保留字,导致识别成内部的方法,网上也有类似的例子


#-*- coding : utf-8 -*-
i = 0
while i <= 100:
               sum += i
               i += 1
print(sum)

sum没有定义,导致同样的错误,TypeError: unsupported operand type(s) for %: 'builtin_function_or_method' and 'int',我的例子中添加了number=0还是抱相同的错误,让我开始考虑这并不是相同的问题,从错误出发,代码把number识别成一个内部的方法,向上找到number的赋值-number=numbers.pop,发现问题出现在pop后面没有括号,如果没有()表示把pop方法赋值给number,而不是把返回值给number,导致代码认为number是一个内部方法,不能做%运算,修改后运行正常。


numbers = [ 12 , 37 , 5 , 42 , 8 , 6 , 7 , 39 , 72 , 68 ]
even = []
odd = []
while   len (numbers) >  0  : 
      number = numbers.pop()
       if (number %  2  ==  0 ):
          even.append(number)
       else :
          odd.append(number)
print ( '单数有:' ,odd)
print ( '双数有:' ,even)



PythonCode/test.py
单数有: [39, 7, 5, 37]
双数有: [68, 72, 6, 8, 42, 12]


注:pop() 函数用于移除列表中的一个元素(默认从最后一个元素开始),并且返回该元素的值

       python3里面有很多类似的细节问题,感觉还是要从初始错误的描述开始,另外养成正确的编程习惯也很重要,尤其是  从python2过度到python3的用户。








来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/11289933/viewspace-2682039/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-09-16

  • 博文量
    23
  • 访问量
    96487