"Patty" <pa...@cruzio.com> wrote

for c in 'abcd':

c takes the value of each letter in turn

When I first looked at this - I thought that the variable 'c' would have had to be initialized first earlier in the program.

It is initialized earluier - in the for statement, each time through the
loop it gets reinitialized to a new value.

... I wasn't thinking counting variable for some reason. So is 'for c in', one or more of key words that Python understands that a loop is here and to actually trigger counting in a loop? Does it start with a 1 or 0 internally to do this?

In the case of a for loop it doesn't count as such.
It takes each value from a sequience and applies it to the
loop variable. Personally I think it wouyld have read better
if they called it "foreach" so your loop would look like

foreach char in 'abcd':

or

foreach item in [1,2,3,4]:

etc...

But they didn't so we are stuck with for.

I also realized a mistake I may have made - maybe I confused 'for c in'

while c in 'abcd':

This is completely different.
In this case we can clarify it by adding some parentheses:

while (c in 'abcd'):

the test is all of the bit in parens. And the test is a test of whether
c is in the string or not. Python does not modify the variable 'c' in
this case, that only happens with a for loop.

You can read more about the various python loop structures
in the loops topic of my tutorial.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to