Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Plus equals +=

Can someone please tell me what the long version of "+=" would be?

for instance with this code:

def add_list(a_list): total = 0 for item in a_list: total += item return total

how could I write total += item the long way?

Thanks,

Tony

4 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher
def add_list(a_list):
    total = 0
    for item in a_list:
        total = total + item
    return total

Thx! I'll get this if it kills me! lol

Hello Kenneth, so we know that the total here will be 6. But how do we access that outside of the function?

I know we can't say print(total) because it's outside of the function.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You have to send information back out of the function. There's a special keyword that does just that. We used it in several videos and I used it above. Any guesses?

Hey Kenneth Love so let's say that a_list = [1,2,3]

The for loop would essentially change the total variable to 1, then run through the for loop again with total = 1

Then do it again, then it'd = 3

Then it'd do it again, then it'd = 6 ?

I think I got it.

return (is what I thought). But when I'm using this in IDLE, I'm getting the following:

print(total) NameError: name 'total' is not defined

Kenneth Love
Kenneth Love
Treehouse Guest Teacher
def add_list(a_list):
    total = 0
    for num in a_list:
        total += num
    return total


my_list_total = add_list([1, 2, 3])
print(my_list_total)

That would print 6. The return makes it so you can assign the output of the function to a variable.

Ok got it. Thanks!