[Tutor] How does it work?
Patty
patty at cruzio.com
Mon Jan 3 20:24:44 CET 2011
Yes, I knew there was something I wasn't getting. This is the explanation I
was looking for - and I'm sorry about the incorrect indentation. And I
agree with Alan that 'foreach' would have been a good name for this type of
loop. I need to sort out 'loop structures' in my notes and read up on
these for sure.
Thanks,
Patty
----- Original Message -----
From: "Dave Angel" <davea at ieee.org>
To: "Patty" <patty at cruzio.com>
Cc: <tutor at python.org>
Sent: Monday, January 03, 2011 9:52 AM
Subject: Re: [Tutor] How does it work?
> 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