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?

TIF
  • 191
  • 1
  • 2
  • 11

3 Answers3

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
blue_note
  • 27,712
  • 9
  • 72
  • 90
1

Use a break statement to escape from a loop

while True:
    if function_output(x) > tolerance:
        break
Tobey
  • 1,400
  • 1
  • 10
  • 25
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 )
ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52