0

I have this code construct:

flag = True
while flag:
    do_something()
    if some_condition:
        flag = False

Is it the best way to do that? Or is there a better pythonic way?

ComputerFellow
  • 11,710
  • 12
  • 50
  • 61

2 Answers2

4
while True:
    do_something()
    if some_condition: break

or

while not some_condition:
    do_something()

For the second option to be equivalent to the first, some_condition must start as False so do_something() will get called at least once.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1
def late(cond):
    yield None
    while cond(): yield None

for _ in late(lambda: condition):
    do_something()

Looks weird. What happens here?

The late() generator forst yields a value in order to enter the loop unconditionally. And in every successive loop run, the cond() is checked.

glglgl
  • 89,107
  • 13
  • 149
  • 217