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 (2015) Logic in Python Around and Around

Subramanian K
Subramanian K
3,103 Points

For 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
Steven Parker
229,771 Points

Your 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
Subramanian K
3,103 Points

Yeah 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
Steven Parker
229,771 Points

But 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.

  1. the first time words has just the letter "a"
  2. the next time it has just the letter "b"
  3. and so on... until it gets to "e"

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".

Subramanian K
Subramanian K
3,103 Points

Now i got that right. My bad. Sorry.