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 somebody explain please more about on topic reassigning the existing variables?

dessert = "chocolates" + " and candy" desert = "donuts" + "snickers"

1 Answer

Steven Parker
Steven Parker
231,269 Points

Note that no reassignment occurs in the code shown here, as "dessert" (with two "s"s) is a different variable than "desert" (with one "s").

But as shown in the video, a reassignment of the same variable normally replaces the contents that the variable had before. This behavior can be changed to add on to existing contents two ways:

  • you can include the variable itself as one of the sources for the value, or
  • you can use the special operator "+=" which adds on instead of replacing

Both techniques are shown in the video.

mohan Abdul
mohan Abdul
Courses Plus Student 1,453 Points

@Steven parker

"you can include the variable itself as one of the sources for the value" what do you mean by this, are you talking about replacing the old variable in this quote?

Steven Parker
Steven Parker
231,269 Points

What I mean is:

dessert = dessert + " and candy"  # this uses the variable as one of the sources
dessert += " and candy"           # this adds on (does the same thing more compactly)