Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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'

4 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

Ryan Caalim
Ryan Caalim
248 Points

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