Reputation: 73
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
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
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
except
) go to the next iteration (with pass
)else
) stop the loopTake 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