0

I've got a piece of code that executes a function, and then based on that output decides if it should reiterate:

while (function_output) > tolerance:
    function_output = function(x)

The problem is that the while loop won't start until "function_output" is defined - but it's defined in the loop. Currenly I've got:

function_output = function(x)
while (function_output) > tolerance:
    function_output = function(x)

but is there a way to get this loop to start without having to iterate the function once already?

11
  • 2
    Emulate a do while? while True: stuff() if fail_condition: break Commented Nov 23, 2018 at 16:36
  • No, python has no "do"-"while" loop Commented Nov 23, 2018 at 16:37
  • function_output = tolerance + 1 before the loop? Commented Nov 23, 2018 at 16:37
  • 3
    @TIF: For what it's worth, your second block of code is the canonical way to do it. Commented Nov 23, 2018 at 16:38
  • 1
    The OP is correct, in thinking that the 2nd way is bad: It has repeated code. Commented Nov 23, 2018 at 16:41

3 Answers 3

2

There is no such thing in python. Neither a do-while, nor a

while (x = f() > 5):
  dostuff

like in C and similar languages.

Similar constructs have been proposed, but rejected. What you are already doing is the best way to do it.

On the other hand, if you want to do it in a do-while style, the proposed way is

while True:
    if f() > tolerance:
       break
Sign up to request clarification or add additional context in comments.

2 Comments

@timgeb: useful (though a bit ugly looking). Let's hope for a do-while too...
1

Use a break statement to escape from a loop

while True:
    if function_output(x) > tolerance:
        break

1 Comment

I think your condition is inverted - that was the condition to continue the loop in the OPs code
0

How about this pattern. You may want to choose a better variable name.

should_continue = True
while should_continue:
    should_continue = ( function(x) > tolerance )

4 Comments

While this is certainly an alternative, it isn't much better than OP's implementation.
@Idlehands is has less repeated code.
@ctrl-alt-delor, What's repeated, a function call? If I had to weight up a repeated function call versus creating a new variable, I know which I'd prefer.
@Jpp I agree if just a function call, but if there are lots or arguments, the I would do it this way. Or encapsulate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.