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
pepoluan
source
to share
2 answers
This seems like a perfectly correct way to implement what you want.
It might be possible to do this more functionally, for example, with two recursive generators, but I suspect that none of them will be as simple as this.
+2
zmbq
source
to share
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
Stephen lin
source
to share