0

Is there a way to evaluate an expression in python and break from a loop in the same time?

Easiest example to explain what I have in mind:

while True:
    if bar == 'baz':
        foo = bar == 'baz'
        break

But that's programmerhorror and I wanted to do something along the lines (maybe with lambda function?):

while True:
    foo = bar == 'baz' # and in the same line call break, but only if bar equals baz
Krzysiek127
  • 29
  • 1
  • 2
  • What's the problem with the `break` being on its own line? Also note that with `foo = bar == 'baz'`, `foo` would end up being either `True` or `False` it's not equivalent to your first code block. – Abdul Aziz Barkat Oct 28 '22 at 15:01
  • If I'd move the break I'd have to do that in an if statement but it could be written better and I made a mistake in first example, it should evaluate to True or False – Krzysiek127 Oct 28 '22 at 15:08
  • Ah, I think what you want is not to repeat `bar == 'baz'`? for example it might be a costly function call instead and you don't want to call it twice? – Abdul Aziz Barkat Oct 28 '22 at 15:10
  • Yes, exactly. And also it just better to not repeat the same code over even if it's a simple comparision – Krzysiek127 Oct 28 '22 at 15:15
  • Does this answer your question? [Can we have assignment in a condition?](https://stackoverflow.com/questions/2603956/can-we-have-assignment-in-a-condition) – Abdul Aziz Barkat Oct 28 '22 at 15:16
  • Not quite, as i would have to return a bool and break from the loop which would honestly complicate the code too much (for example ":= operator" + if foo: break) – Krzysiek127 Oct 28 '22 at 15:35
  • How is `if foo := bar == 'baz': break` too complicated? – Abdul Aziz Barkat Oct 28 '22 at 15:43

2 Answers2

1

add your condition into the while clause itself:

while bar != 'baz':
    # do something
    continue

# now bar = 'baz'
foo = bar
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
1

To extend @C.Nivs answer for the updated question where you want to have foo be a boolean than do:

foo = False
while not foo:
    foo = bar == "baz"

Or if you are on Python 3.9 or above you can use the walrus operator and do:

while foo := bar == "baz":
    continue  # or do something
Matteo Zanoni
  • 3,429
  • 9
  • 27