为什么变量名“sum"导致错误 [Python] [英] why variable name "sum" cause error [Python]
问题描述
我为 Leetcode 问题
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while(1):
if num in list( range(0,10) ):
return num
sum = sum( int(i) for i in str(num) )
num = sum
它产生了一个错误Line 11: UnboundLocalError: local variable 'sum' referenced before assignment
.它是通过将变量 sum
更改为 sum1
来修复的.
It yielded an error Line 11: UnboundLocalError: local variable 'sum' referenced before assignment
. It was be fixed by changing variable sum
to sum1
.
sum
不在 非法变量列表中名称(关键字)(第 2.3 节).
sum
is not in the list of illegal variable names (keywords) (section 2.3).
为什么会出错?是不是,当python看到sum = sum(...)
时,python开始把sum
当作一个变量而忘记它是一个函数?
So why error? Is it that, when python sees sum = sum(...)
, python starts to treat sum
as a variable and forget it's a function?
推荐答案
您绝对可以将变量称为sum"、file"和reduce".如果您在全局范围内执行此操作,它确实会起作用.例如:
You can definitely call your variables "sum","file" and "reduce". And it will really work if you are doing it in the global scope. For example :
In [6]: sum = sum(range(1,10))
sum 将等于 45,一切都很好.(尽管您不能再使用函数 sum.)
sum will equal 45 and everything is great. (Despite the fact you can't use function sum anymore.)
但是当您尝试在函数内部使用它时:解释器为函数内部定义的变量定义了它自己的范围.
But when you are trying to use this inside the function : interpreter defines it's own scope for variables defined inside the function.
In [2]: def f():
print type(sum)
sum = sum(range(1,10))
f()
您可能期望答案是builtin_function_or_method",但实际上您会得到与上述相同的错误.希望有人对python解释器的细节提供更好的解释.
You may expect the answer will be "builtin_function_or_method" but actually you will get the same error as above. Hope someone will provide better explanation for the details of python interpreter.
这篇关于为什么变量名“sum"导致错误 [Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!