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

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

1 Answer

Steven Parker
Steven Parker
210,872 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
210,872 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)