LISTS AND FUNCTIONS Iterating over a list in a function 15/18


#1

LISTS AND FUNCTIONS - Iterating over a list in a function 15/18

An error message has appeared:
total([0, 3, 6]) returned 15 instead of 9

n = [3, 5, 7] should result in 15, so why my code is wrong? Any ideas would appreciate. Thank you!

n = [3, 5, 7]
def total(numbers):
	result = 0
  	for i in range(len(n)):
    		result = n[i]+result
	return result



#2

Hi @olek_iprospect,

The function parameter is numbers, and within the function, you should work with that variable instead of with n. As the function executes, numbers will refer to whatever list was passed to it when the function was called.


#3

I’ve replaced it with the following code

n = [3, 5, 7]
def total(numbers):
	result = 0
  	for numbers in range(len(n)):
    		result = n[numbers]+result
	return result

An error message has remained the same: total([0, 3, 6]) returned 15 instead of 9


#4

Here is the way my function has actually worked

n = [3, 5, 7]

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

print total(n)

Thanks for your help anyway!


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.