0 points
Submitted by New User
over 6 years

15/18 Iterating over a list in a function Method 1

Since we aren’t modifying the list, feel free to use either one on this lesson! Create a function that returns the sum of a list of numbers. Create a function called total that adds up all the elements of an arbitrary list and returns that count, using the existing code as a hint. Use a for loop so it can be used for any size list.

My code is:

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

Why it dosn’t work? err msg: Traceback (most recent call last): File “python”, line 8, in

I got no problem with Method 2

Answer 552a94489113cb25f500061e

3 votes

Permalink

Answer is:

n = [3, 5, 7]
def total(numbers):
    result = 0
    for i in numbers:
        result += i
    return result
print total(n)
points
Submitted by spilogale
over 6 years

Answer 55245499d3292f982b000185

1 vote

Permalink

you’re adding items to the original result so you only need it to look like

result += i

points
Submitted by Catherine Click
over 6 years

Answer 552acc07d3292fa0cb000539

1 vote

Permalink

n = [3, 5, 7]

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

print total(n)

Works both.

points
Submitted by kamrad
over 6 years

Answer 5523d3bce39efe4e2e0002df

0 votes

Permalink

i will take on the numbers: 3 5 and 7 as the loop goes. using those numbers as indexes will cause index-out-of range. a for-loop does not produce indexes it directly supplies you with each element

points
Submitted by Jonatan
over 6 years

1 comments

New User over 6 years

How code should look if we use method 1?

Answer 55371adee39efee08d000332

0 votes

Permalink

enter code here

n = [3, 5, 7]

def total(x): total = 0 for i in range(len(x)): total = total + x[i] return total
indent first two lines inside function once, indent third twice ans last once)

points
Submitted by Markus Wagner
over 6 years