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 trialBrendan Ballon
Courses Plus Student 2,728 PointsHow exactly does this while loop work?
it says:
"var index = 1
while index < { print("random sentence") index += 1 }"
I'm mostly confused about what "+=" does and how it will only print the array and not the string.
1 Answer
Alex Koumparos
Python Development Techdegree Student 36,887 PointsHi Brendan,
First, there is a small typo in your example code: you haven't included a value for the index to be compared to. For illustration I've used the value 3.
Here is the corrected while loop:
var index = 1
while index < 3 {
print("random sentence")
index += 1
}
This code will print "random sentence" twice. It won't print an array (as there isn't one in this code snippet).
The index += 1
is a shortcut for writing: index = index + 1
. Any time you see a mathematical operator (+,-.*,/) immediately followed by the assignment operator (=), it means "take the value in the variable to the left of the operator, apply the math operator with the value to the right, then put that new value back in the variable".
In the while loop above, the variable index starts with the value of 1. Then we go into the loop (because 1 is less than 3), we print the string, then index gets increased by 1. Since 2 is still less than 3, we go back into the loop and print the string again. Again, index gets increased by 1. It is now no longer less than 3, so the loop exits.
Hope that clears things up.