More elegant way to try running a function X times?

Sion Arrowsmith siona at chiark.greenend.org.uk
Wed Nov 19 09:37:06 EST 2008


Gilles Ganault  <nospam at nospam.com> wrote:
>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()
>=====

for i in range(5):
    if CheckIP():
        break
else:
    print "Exiting."
    sys.exit()

Note very carefully that the "else" goes with the "for" and not the "if".

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list