NH8
NH8

Reputation: 73

Retrying a failed loop Python

I'm running a code which runs a simulation for a given N value. I am trying to add a while loop in to retry the loop under a new N value if it fails. For example, if it fails for N=10, I want it to increase to N=20 and so on until it doesn't fail. At the moment I have:

N=0
while True:
    N=N+10
    simulation(N)
    break

I'm not entirely sure if I'm using 'True' correctly (I was taking it to be it runs until it doesn't fail?). I've looked at other posts asking similar things and the solutions were using exceptions, but that was when they already knew where exactly there would be a failure, whereas I don't know what values of N will fail.

Upvotes: 1

Views: 495

Answers (2)

Ketan Mukadam
Ketan Mukadam

Reputation: 859

If you know the return value of simulation function, you can use it as a check if it passes or fails

N=0
while result:
    N=N+10
    result = simulation(N)

Assuming that simulation will return False when it passes else return True. You can negate the check if it is other way round. You should have another boundary check on N to exit the while loop, in case simulation does not pass for any values of N.

I also recommend to catch any exceptions to avoid ungraceful exit similar to above answer.

Upvotes: 0

blue note
blue note

Reputation: 29081

Depends on what you mean "fails". A possibility would be

N=0
while True:
    N = N+10
    try:
       simulation(N)
    except SomeError:
       pass
    else:
       break

That means

  1. call the simulations
  2. if it goes wrong (except) go to the next iteration (with pass)
  3. if it succeeds (else) stop the loop

Take note that else in python can be used with try and for, but has totally different meaning than the if-else which appears in every language.

Upvotes: 4

Related Questions