"Stephen McInerney" <[EMAIL PROTECTED]> wrote

> Sorry I meant to pick a tangible example to focus the discussion:
>
> This one cannot be (easily) translated to use Python's range()
> operator for (i=30000; i>0; i=i/2) { ... }

You have to remember that C's for loop is mostly syntactic sugar
over a while loop:

expression1
while test
    action
    expression2

becomes

for (expression1,
      test,
      expression2)
     action

Pythons for loop is a much more powerful foreach construct
intended to deal with collections. C's for loop is simply an extension
of assembler syntax and deals with indices, memory addresses, numbers,
whatever low level construct you want. The loop used for that kind
of low level detail in Python is, as you say, the while loop.

> So do you need to know a whole armory of other functions to use
> to generate iterators, or just translate to a while-loop already?

It's very rare that you need to do those kinds of tricks in Python,
usually you avoid the issue entirely by using higher level data
structures.

You don't give us any reason why you want to generate a set
of numbers from 30,000 down to zero decreasing by half each
time: 30,000, 15,000, 7500, 3750, etc

To understand the Pythonic solution to the problem we would
need to know what those numbers were required for so that we
could determine if another python data structure might be more
appropriate.

One of the challenges for C/C++ programmers in moving to
higher order languages like Python (or Lisp, prolog, Smalltalk
etc) is to stop thinking at the machine level and start thinking
at the problem level. Of course sometimes you need to work
at the lower levels and for those cases the while loop can
be used, but it tends to be the exception rather than the rule.

As to your particular case one non while option would be a generateor:

def half(n):
    while int(n) > 0:
       n = n/2
       yield n

for x in half(300): print x,

But without a context for x its impossible to know ewheher
that is a sensible solution.


HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to