YJZ
YJZ

Reputation: 4214

why variable name "sum" cause error [Python]

Hi I did the following code for a Leetcode question

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

It yielded an error Line 11: UnboundLocalError: local variable 'sum' referenced before assignment. It was be fixed by changing variable sum to sum1.

sum is not in the list of illegal variable names (keywords) (section 2.3).

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?

Upvotes: 2

Views: 5922

Answers (3)

Srgrn
Srgrn

Reputation: 1825

UPDATED with consideration for comments below

sum is a built-in function (which you use on line 11)

so you cannot should use it as a variable name https://docs.python.org/2/library/functions.html

The following is a bit too much of an opinion

The error is a bit unclear in this case as the interpreter tried to use sum as a variable instead of a function.

Upvotes: -3

Karoly Horvath
Karoly Horvath

Reputation: 96306

sum is a built-in function. This is not a problem in itself, as you can reassign it, e.g. the following works just fine:

sum = 1

The problem is that it's also on the right hand side of the assignment in a function:

sum = sum( int(i) for i in str(num) )
      ---

Since you're using sum as a local variable, the name on the right hand side will also refer to this local variable (and not to the built-in function). At this point you haven't given it any value yet (it's before the assignment), yet you're trying to use it, so it's an error.

Just give your variable a different name.

Upvotes: 5

ig-melnyk
ig-melnyk

Reputation: 2879

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 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()

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.

Upvotes: 7

Related Questions