How does Python know what character my loop variable currently is?

Question

How does Python know what character my loop variable currently is?

Answer

When we create a for loop and create some named variable after the word for, Python knows to assign that variable the value of each thing we’re iterating over in the iterable object given to the for loop after the word in.
For example, if we have for character in some_word:, character will hold the value of each individual character until there are no characters left in some_word.
It doesn’t “know”, by any means. Python just expects something it can iterate through, and then assigns each current item to the variable and that’s what you’re given to work with.

6 Likes

Please see the below code and tell me why this is being printed out

thing = “spam!”

for c in thing:
print c

word = “eggs!”

Your code here!

for w in word:
print c

I think the problem is you used “w” as each character in word, but then under the for loop, you told it to print “c” instead of “w”.
I’m not sure what you’re asking for though because I can’t see your console in your comment.

I did the exercise as instructed and my output:
ps

ma

e!

gg

!s

… is a bit confusing. it says it should print each individual character, not two at a time, and not backwards…

my code for reference:
thing = “spam!”

for c in thing:

print c

word = “eggs!”

Your code here!

for c in word:

print c

In this snippet there are two problems: 1)You forgot to indent the 2nd line, thus your code must be:
for w in word:
print w
2) when printing you must use the same letter that you used in for

I have tried your code and is correct, anyway here below you can check:
thing = “spam!”

for c in thing:
print c

word = “eggs!”

for c in word:
print c