Iterating over a list in a function


#1

I need some help figuring it out what is wrong with my code, I have been having trouble with indenting code and I think that might be the case in this exercise.

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

#2

Let’s start with your for loop. You want to loop through (iterate) the numbers that are passed into the function. Then you want to add each number to the total that you are storing in result.

Think about that. How would you loop through the numbers and then add each one to the total result?


#3

So just to understand what the answer should be, the answer should be 15 because we want to add all of the numbers and store them in results right ?


#4

I got this exercise to work with the following code, however this spits out 15 ( the same result that my previous code outputs) as an answer. Why was my previous code incorrect then ?

n = [3, 5, 7]

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

#5

You are receiving a list of numbers. Why don’t you just loop through those numbers instead of using range.

for number in numbers:

Think about it.


#6

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