# Iterating over a list in a function

#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>

```python

Replace this line with your code.

``````<do not remove the three backticks above>

n = [3, 5, 7]

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

I honestly do not know how this part works if someone can explain please.

Instructions:
1.
Create a function that returns the sum of a list of numbers.

On line 3, define a function called total that accepts one argument called numbers. It will be a list.

Inside the function, create a variable called result and set it to zero.

Using one of the two methods above, iterate through the numbers list. For each number, add it to result.
Finally, return result.

#2

We want to add each value to the result, in turn…

``````result += i
``````

Be sure that the return statement is not inside the loop.

#3

One thing I am struggling with is trying to understand the loop. I know how to define a function
def and make and argument(). I also know how to create a loop
for, in.

I don’t know f you could explain to me how this part works
result += i
what does it do? I understand >=, !=, >, <, <= but +=? this does not make sense to me.

Thank you.

#4

Those are all comparison operators.

``````+=
``````

is a compound assignment operator. Consider the following:

``````result = result + i
``````

In the above, a new value is created using both `result` and `i`. This new value is then assigned back to the original variable, replacing its old value with the new one. We can do this two step process with a single operator…

``````result += i
``````

The process is identical to the one above, only shortened to make the code more readable.

Any math operator can be written in compound form.

``````+
-
*
/
``````

are the most common, but we can also write compound form of,

``````//
%
**
``````

We can even use the compound form on bitwise operators (but you will rarely see this).

``````&
|
<<
>>
``````

The main thing to keep in mind is that the variable on the left is being re-assigned with the new value.

``````>>> a = 12
>>> a <<= 2
>>> a
48
>>> a >>= 2
>>> a
12
``````

#5

Now it makes more sense.
Thank you.

#6

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