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)
print(addition([1,2,3,1,2,1]))
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
print(addition([1,2,3,1,2,1]))
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?
(as explained in the answers below, it had nothing to do with variable scope so I changed the title to reflect the issue, for anyone happening on this in the future)
if data: return data.pop() + addition(data)withelse: return 0as the base case. You wouldn't need thetotalargument at all, since the actual addition happens with the return values.def fib(data): if data > 1: return fib(data-1) + fib(data-2) elif data == 1: return 1 else: return 0 print(fib(15))yup, got the idea and I now totally understand why the return statements were also necessary