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 trialSubramanian K
3,103 PointsFor loop doubt
I am have a variable which contains a string. Then i run a for loop to print the string and saved it into another variable. But when finally the for loop runs successfully. When i print the new variable it is showing only the last character in the string. May I know what is happening.
>>> check = "abcde"
>>> for words in check:
. . . print(words)
. . .
a
b
c
d
e
>>>words
'e'
2 Answers
Steven Parker
231,236 PointsYour loop puts one letter at a time into "words".
For each time the loop runs, it takes one letter out of check and puts it into the variable words. Then it prints that letter, which you see in the example above.
After it has done this with each letter the loop ends. But the value in words is still the last letter that was put there by the loop, in this case: "e".
Subramanian K
3,103 PointsNow i got that right. My bad. Sorry.
Subramanian K
3,103 PointsSubramanian K
3,103 PointsYeah but not words variable has all the letters from the string. then why should it print only the last letter in the group. Thanks in advance.
Steven Parker
231,236 PointsSteven Parker
231,236 PointsBut words never has all the letters from the string. Your loop puts just one letter in it at a time. You can see this from the letters shown to you by the print(words) in the loop.
The name "words" might not be the best choice for that variable, based on what it is being used for. A better name might be "letter" or "OneLetter".