I am trying to:
Implement an iterative Python function which returns the sum of the first n integers
so far i have this:
i = 0 total = 0 def sum(n): while i <> n: total = total + 1; i = i + 1; return total
then later when i try to used
sum(5) i get this error message:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
File "<pyshell#7>", line 2, in sum
while i <> n:
UnboundLocalError: local variable 'i' referenced before assignment
now if i change my code from total = total +1 to just total +1
(and the same for i = i +1)
that error message doesnt come up anymore but the answer to any sum(n) is always 0.
I am confused as to why this is happening.
local variable 'i' referenced before assignment probably has something to do with it but if someone could explain why this is happening id be very grateful.
Thanks in advance and try to keep it simple for me ^^ haha