关于python报错:TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'

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

上述代码报错:

TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'

关于上述提示错误:是因为在Python中不需像C一样,需要 int sum (指定sum的类型),但并不是说可以直接放在表达式中去计算,所以还是需要先定义的(这些都是小细节,平时都应该尽量避免,做好类似问题的收集),即正确的代码如下所示:

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

 

 

 

 

 

你可能感兴趣的:(Python)