How does Python know what letter is?


How does Python know what letter is?


In the example below, letter is just the variable name we chose to represent each item in whatever the loop is iterating through.

for letter in word:
  # Only print out the letter i
  if letter == "i":
    print letter

Python doesn’t know what letter is, because it’s simply the name we chose for our loop variable. We could have named it pizza or character - anything. The name should be something that tells us what it is, though. letter accomplishes just that.


In the example shown above we check if each letter is i.
But that doesn’t explain how does Python know what letter is?
If we remove the if statement I know it will print out each letter but I don’t know why.

its literally in this FAQ:

python now will assign values from the string to this loop variable.

String type stored as character based.
‘word letter’ is string type, each element in string is a letter(or space in this example)
[‘word’,‘letter’] is list type, each element in list is a string(like ‘word’)
when you run for loop, it starts from the very first element, it doesn’t recognize letter, but very first character in string.


Different quiestion about the same code - where in the code is it being instucted to print each letter o a different line?

the default behavior of the print statement is to print the output on a new line


Thank you! Appreciated :slight_smile:

thank you for actually explaining it and not just saying its the variable. :smiley:

1 Like