Python Forum
for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: for loop (/thread-7259.html)



for loop - Wolfpack2605 - Dec-31-2017

I am not quite sure why for loops work this way. Why do you write for colour in colours and then print colour. It is confusing me.
colours = ['red', 'blue', 'green']
for colour in colours:
  print(colour)
Output:
red blue green



RE: for loop - metulburr - Dec-31-2017

printing it is just the action. colour is the variable created for every index in that sequence of colours.

for every index in sequence:do something


RE: for loop - mepyyeti - Jan-01-2018

It's intended to be 'easier' to understand. As you gain experience this style will make understand code easier.

But for our experience level, I think it just causes confusion...

Basically you have your individual 'elements' in your colour list. You basically tell the loop to iterate (count) through each element in the list. So you need a place holder for each, individual element. "colour" is that place holder

in other words:
colour =['foo','bar','moo'] #element names don't matter for this example
for c in colour: #read as for each element in your colour list
   print(c)  #print THAT SPECIFIC ELEMENT
the only thing that you have to make sure is that the variable you print © is the same variable that is acting as place holder.

in other words:
colour =['foo','bar','moo'] #element names don't matter for this example
for c in colour: #read as for each element in your colour list
   print(x)  #you get an error bc c is NOT x
will not work.