(I accidentally sent this to the originator. Sorry.)

Sweet! 

Almost everything is sooo familiar, yet, merged in many interesting ways. I never had a DO WHILE statement, but
in many ways, your further examples are like a combination of my old FOR NEXT loop and IF logical evaluation statement put together for reading in/out lists. JUST TOO COOL!

And it looks so CLEAN!  --compared to my old BASIC of having to name the variable belonging to each NEXT incrementation executed while keeping the code nested properly relative to each FOR NEXT loop!!!

Thanks!  THIS LOOKS GREAT!

Terry



On Fri, 2005-11-11 at 11:49 +1300, John Fouhy wrote:
On 11/11/05, Terry Kemmerer <[EMAIL PROTECTED]> wrote:
>  I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A
> Computer Scientist" and I still can't count.
>  (Don't laugh! I can't play the violin either...)
>
>  In Basic, I would have said:
>
>  10  x = x + 1 :  print x : goto 10
>
>  run
>  1
>  2
>  3
>  etc....
>
>  How is this done in Python? (So I can stop holding my breath as I study
> this great language....and relax.)

Hi Terry,

There's a couple of options.

First, we could do it with a while loop.  This is not the best or the
most idiomatic way, but it's probably most similar to what you've seen
before.

#### count forever
i = 0
while True:
    print i
    i = i + 1
####

Of course, we generally don't want to keep counting forever.  Maybe
we'll count up to 9.

#### count to 9
i = 0
while i < 10::
    print i
    i = i + 1
####

A while loop contains an implicit "GOTO start" at the end.  At the
start, it checks the condition, and breaks out of the loop if the
condition is false.

Like i said, though, this is not idiomatic Python.  Python has for
loops which are based around the idea of iterating over a sequence. 
So, we could count to 9 like this:

#### count to 9
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
    print i
####

The loop will go through the list, assigning each item to i in turn,
until the list is exhausted.  The range() function is useful for
building lists like that, so we don't have to type it out manually.

#### count to 9
for i in range(10):
    print i
####

And, of course, once we've got range(), we can give it a variable
limit (eg, n = 10; range(n)).  Iteration is the key to doing all kinds
of funky stuff in python (including new ideas like geneartor
functions), so it's good to get the hang of :-)

--
John.
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to