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 Python Basics Types and Branching Strings and Operators

Can someone please help me, im trying to understand what += does in this code

can someone please help me with this question im trying to understand what the += is used for.

https://teamtreehouse.com/library/strings-and-operators

snacks = "cake" + " and custard"
snacks = snacks + " and tea"
snacks += ", lovley"
snacks
'cake and custard and tea, lovley'

5 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Jamshaid Ali! The += is really just a shorthand. It means, take the value that was in this variable, add something to it and reassign it back into that variable. The result is cumulative.

greeting = "Hi"
greeting += " there, Jamshaid"
greeting += "!"

print(greeting)

This will print out "Hi there, Jamshaid!". Each time we use the += we're taking the original value and adding on a new string to the end. But you could also write this out the long way:

greeting = "Hi"
greeting = greeting + " there, Jamshaid"
greeting = greeting + "!"

print(greeting)

This would give you the same results. Take the original value. Add something to it and assign the result back into the variable overwriting the original value with the cumulative value.

Hope this helps! :sparkles:

let's say
a = 2

a=a+3 -------The value of a will be equals to 5.

instead of writing a=a+3, we can also write a+=3. The result will be the same.

ok thank you

Thank you for breaking it down. I understand it now too

Anders Beutler
PLUS
Anders Beutler
Courses Plus Student 606 Points

another way to see it... think of the " + " in the equation there would be considered you adding another string to the pre-existing string. Then the " = " would be considered you applying both together. So essentially, "dessert += "!" * 20" really just means "add (whatever dessert was for you) the dessert string to this new one, "!", and apply them together. equaling (my dessert)... Strawberries and Bananas and Ice Cream, yum!!!!!!!!!!!!!!!!!!!! .