What's the pythonic way to "repeat this until the condition reaches its maximum"?
I'm still learning Python, and I'm wondering if there is a "more Pythonic" way for the following:
MAX_ATTEMPTS = 5
for i in range(MAX_ATTEMPTS):
response = do_something()
do_something_based_on(response)
do_another_thing_based_on(response)
if response == 0:
do_something_if_success()
break
Edit: Sorry, I could simplify this case. I need to use response
before final check, so I have to write it in a variable.
+3
source to share
2 answers
I think this way will save more memory than yours:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
MAX_ATTEMPTS = 5
for i in xrange(MAX_ATTEMPTS):
if 0 == do_something():
do_something_if_success()
break
EDIT:
Updated according to the latest quesiton.
MAX_ATTEMPTS = 5
for i in xrange(MAX_ATTEMPTS):
response = do_something()
do_something_based_on(response)
do_another_thing_based_on(response)
if 0 == response:
do_something_if_success()
break
+3
source to share