Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for loop
#1
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
Reply
#2
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
Recommended Tutorials:
Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020