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
Tony Brackins
28,766 PointsPlus 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
Treehouse Guest Teacherdef add_list(a_list):
total = 0
for item in a_list:
total = total + item
return total
Tony Brackins
28,766 PointsHey 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.
Tony Brackins
28,766 Pointsreturn (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
Treehouse Guest Teacherdef 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.
Tony Brackins
28,766 PointsOk got it. Thanks!
Tony Brackins
28,766 PointsTony Brackins
28,766 PointsThx! I'll get this if it kills me! lol
Tony Brackins
28,766 PointsTony Brackins
28,766 PointsHello 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
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherYou 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?