15/18: Why not?


Actually, I feel like I'm not learning anything! I need the forum over and over again.
What is going wrong this time? I says that result in line 10 is not defined, but result=0, every i is added to result and result is returned so what's the problem?

n = [3, 5, 7]
n = [3, 5, 7]

def total(numbers):
(indent) result=0
(indent) for i in numbers:
(indent indent) result+=i
(indent indent) return result

print result


@methodslayer18884 take a look at the excerpt below on why you are getting that error

n = [3, 5, 7]
#n = [3, 5, 7]

def total(numbers):
    #you create a variable result
    #this variable is local to this function
    #ie.only exist when this function is called(used)
    for i in numbers:
    return result

#now you call the function on the list n
#you created outside the function
#you need to call print on it to see the result
#in the console
print total(n)

#here you are printing a variable that does not
#exist remember the result variable in the function
#total will only exists when the function is called and 
#will be used only internally(locally) for the computations
#in the fucntion
#hence you get the error

#comment it out
#print result


The above reply is more accurate. But here's another way to do it.

n = [3, 5, 7]

def total(numbers):
result = 0
for x in range(len(numbers)):
result += numbers[x]
return result

print total(n)