Python Question

Python: variable scope within function

As an exercise, I was trying to make a script that would give me the sum of the items in a list but without using SUM or FOR/WHILE loops.

I ended up solving it with:

def addition(data, total=0):
if data:
total += data.pop()
return total if data == [] else addition(data, total)


This works well and returns '10', but my initial approach was:

def addition(data, total=0):
if data != []:
total += data.pop()
addition(data, total)
return total


and this second bit of code returns '1' instead of '10'. I can't figure out why the two approaches aren't doing the same thing or even where the second example comes up with the '1' as it enters the final loop with data = [] and totals = 10, I'm guessing that I'm missing some rule regarding how variable scopes work?

(I went over variable scopes again before asking the question and I can't find anything that seems applicable)

Answer Source

In the second function, when you call addition(data, total), a copy is made of variable total and it is therefore not modified in the calling function.

Only the first element to be popped, 1, is added to total before the function returns. For it to do the same thing, you would want to replace addition(data, total) with return addition(data, total).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download