looping

John Hunter jdhunter at ace.bsd.uchicago.edu
Fri Jun 20 15:07:01 CEST 2003


>>>>> "Lucas" == Lucas Raab <lvraab at earthlink.net> writes:

    Lucas> I'm a newbie and I can't figure out how to loop from the
    Lucas> end of the program back to the beginning. Any suggestions?

Welcome to python!

There are a number of ways to do it depending on your needs.  If you
need to loop a fixed number of times, use a for loop

  for i in range(10):
    print i
    # do some more stuff, at the end, it loops back

If you need to loop back an arbitrary number of times until some
condition is met, use a while loop

  while 1:
    print 'hi mom'
    # do some more stuff
    if some_condition:
       break   # this ends the loop
  
    # do some more stuff and then the program will loop back


You may also want to put the stuff you want to loop over in a function

  def somestuff():
     print 'hello again'
     #do some more stuff

Now you can call 'somestuff' whenever you need to, in a loop or in
response to some event, and you code will be rerun, eg,

  for i in range(20):
     somestuff()

Take a look at the python tutorial,
http://www.python.org/doc/current/tut/tut.html, particularly the
section on control flow:
http://www.python.org/doc/current/tut/node6.html

John Hunter








More information about the Python-list mailing list