When do we need to define variables in loops?

Why is the line “total = 0” necessary in this code?

def sum_to(n):
    total = 0  # <<< this line
    for i in range(n):
        total= total + i
    return total

Also, I’ve noticed the same for “while” loops and was just wondering if that statement represents the starting number (which is 0), or just as a a way to introduce a foreign variable into an inbuilt function.

Thank you!

Answer

It initialises the variable to a starting value before it is modified by the loop. Consider the alternative without it:

def sum_to(n):
    for i in range(n):
        total = total + i

    return total

On the first iteration of the loop it is asked to perform total + i, but it has never encountered total before and thus has no value it can possibly use for it.

If you ran that modified function you would get an error

UnboundLocalError: local variable 'total' referenced before assignment

telling you that you are attempting to access a variable that has never been assigned a value. In this case Python can see that you are eventually going to give it a value, hence “before assignment”. In a different context where this is not true the error might be

NameError: name 'total' is not defined

which means the variable is completely unknown.