Iterating over a list in a function


#1



--------------------------------------------------:arrow_down:

What am I doing wrong? I'm kinda stuck :rage:
Huurm

:rage:
:rage:
Here is the link - - - - - - - - - - - - - - - - - - - - - - - - :arrow_down:
https://www.codecademy.com/courses/python-beginner-nzzVa/3/4?curriculum_id=4f89dab3d788890003000096


This is the error:

 Oops, try again. Your code looks a bit off. Check the console window for errors!

and here is the console:

  File "python", line 6
    for number in numbers
                         ^
SyntaxError: invalid syntax

and here is the code ------- :arrow_down:

n = [3, 5, 7]

def total(numbers):
    result = 0
    numbers = [1, 9, 6, 10]
    for number in numbers 
    result + 1
    return result


#2

Add a colon after the for loop
( for number in numbers: )


#3

You're indentation is off. Also, you add one to result but then you don't store it anywhere.


#4

for result, try;
result +=number


#5

Alright, once you fix the colon, you'll have this.

for num in range(0, len(numbers)):
(indent) result += numbers[num]
return result

When using range method, you have to remember that you are dealing with index(or indices in plural). Thus, you have to include the index in a list, to access it


#6

Error: :arrow_down:

Oops, try again. total([0, 3, 6]) returned 26 instead of 9

Code: :arrow_down:

def total(numbers):
    result = 0
    numbers = [1, 9, 6, 10]
    for number in numbers:
        result += number
    return result

#7

Hmm, I added a range() into it... still not working :rage:


#8

That seems fine. Just delete numbers = [1, 9, 6, 10]. You are basically outputting ONLY 26 if you had that in.

EDIT:

Your number in your for loop is an index for the list, numbers. So you need to add it into result += number like this:

result += numbers[number]

#9

Don't add any lists. Use the one given. It will work


#10

Here's how I did it.


#11

Thank you. I was banging head against wall until you screen shot made me realize I had the indent on the return too far over.


#12

I'm not gonna steal your code mate :slight_smile:


#13

Okay fine... I stole your code because I'm stuck for so long :rage:


#14

But not all of you code :slight_smile:


#15

@blogsolver80984
Thanks for the help
@datfatcat
you really helped a lot :') THANKS
@aquaphoenix17
You helped me (a little bit) thanks :slight_smile:

To all those that helped me THANK YOU!!!!!!!!!!!!!!!!!!!!!!!!! :slight_smile:


#16

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