[Tutor] How does it work?

Dave Angel davea at ieee.org
Mon Jan 3 18:52:50 CET 2011


On 01/-10/-28163 02:59 PM, Patty wrote:
> <snip>
>>>>>>> for c in 'abcd':
>>>
>>> ......
>> When I first looked at this - I thought that the variable 'c' would
>> have had to be initialized
>> first earlier in the program. And I thought that the programmer would
>> input a single char or a single space. 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?
>>

There's not necessarily any integer indexing going on.  for xxx in yyy
is a specific syntax that specifies a loop based on a sequence.  In this 
case the string 'abcd' is a sequence of chars, so you get c to have a 
value of 'a',  'b',  'c', and 'd'.  But other sequences might not have 
any index meaning at all, so it doesn't make sense to ask if it's 0 or 1 
based.  For example, you can iterate over the keys of a map, where the 
order is irrelevant.  All you really know is you'll get them all if you 
finish the loop.

>> I also realized a mistake I may have made - maybe I confused 'for c
>> in' with 'while c in'.
>>
>> r=''
>> c="d"
>> while c in 'abcd':
>> r=c+r
>>

You messed up the indentation.  But if the r=c+r line is indented, then 
this is an infinite loop.  It'll quit when memory is exhausted.  Why? 
Because nothing in the loop changes c.  So since it's in the sequence at 
the beginning, it will always be.

>> Or
>>
>> r=''
>> c="d"
>> while c in ['a', 'b', 'c', 'd']:
>> r=c+r
>>

Similarly here.

>> Also for myself I think I would have used different descriptive names
>> for variables so that would have been less likely to throw myself off.

Good idea.

>> And also doing this fast to see if I have learned.
>>
>> I really feel comfortable with Python now after six months and my
>> small application is completed and looks really good. I don't know how
>> I would have been able to make the simplest, smallest GUI part of my
>> application - using Tkinter and PIL- fast without the references and
>> explanations of Wayne Werner and Alan - Thanks to those on the list
>> who are so helpful!
>>
>> Patty
>>

HTH

DaveA


More information about the Tutor mailing list