[Tutor] FOR loops

Deirdre Saoirse deirdre@deirdre.net
Sat, 2 Oct 1999 11:07:07 -0700 (PDT)


On Sat, 2 Oct 1999, R Parker wrote:

> Hello, I am a beginner at python and have been learning it from the
> O'reilly book 'Learning Python'
> it has been pretty easy to understand for someone who has never
> programmed before, but it stumps me sometimes.......Thats where this
> message comes in, I got to the part that introduces FOR loops
> the book doesn't explain the concept very well and I don't understand
> how to use FOR loops in my programs.Could anyone explain what FOR loops
> do and how to implement them in my programming?? I would really
> appreciate it.

When you want to do a for loop, you have to have a range of
numbers for which you want to execute the loop. If you wanted to do it ten
times, a common way of doing it would be:

for i in range (0,10):
 print i

If you wanted to do it for several arbitrary numbers, you could also do it
without a range parameter:

for i in [6,12,18,24]:
 print i

(the range can also be enclosed in parentheses rather than square
brackets)

You can also be fancier:

def fibonacci(endval=50):
 a = [1, 1]
 while 1:
  z = z = a[len(a)-1] + a[len(a)-2]
  if z < endval:
   a.append(z)
  else:
   break
 return a

for i in fibonacci(50):
 print i


-- 
_Deirdre   *   http://www.linuxcabal.net   *   http://www.deirdre.net
"I must say that I was really happy to see _Linux for Dummies_ -- that's 
when you know you've arrived." -- Linus Torvalds