More elegant way to try running a function X times?

Banibrata Dutta banibrata.dutta at gmail.com
Thu Nov 20 13:35:59 EST 2008


On Thu, Nov 20, 2008 at 11:58 PM, Steve Holden <steve at holdenweb.com> wrote:

> Gilles Ganault wrote:
> > Hello
> >
> > As a newbie, it's pretty likely that there's a smarter way to do this,
> > so I'd like to check with the experts:
> >
> > I need to try calling a function 5 times. If successful, move on; If
> > not, print an error message, and exit the program:
> >
> > =====
> > success = None
> >
> > for i in range(5):
> >       #Try to fetch public IP
> >       success = CheckIP()
> >       if success:
> >               break
> >
> > if not success:
> >       print "Exiting."
> >       sys.exit()
>
> Use the for statement's "else" clause: it's there to allow you to
> specify code to be executed only when the loop terminates normally.
>
> for i in range(5):
>    if CheckIP():
>        break
> else:
>    sys.exit("Could not verify IP address")
> ... remainder of program ...
>

and possibly use 'xrange(5)' instead of 'range(5)' ...

-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081121/430f3dc3/attachment-0001.html>


More information about the Python-list mailing list