How can I write Python script to combine while
s with if
s and break
entire nested-loop if condition met?
I have read other topics, but I cannot get script working...
How can I wrote this script to exit or break all nested-loops, when if
condition is met?
Script:
breaker = False
while True:
...commands...
if ... :
...commands...
if ... :
...commands...
while True:
...commands...
if ... :
if ... :
breaker = True
break # ...to exit all loops
i = 1
j -= 1
if breaker:
break
...continue script here if `break`
CodePudding user response:
For each if statement you need to close it with an else each one need to have one otherwise I don't think the code will work and that last (j-=1) I think it has to be on top of the last (if breaker:) code you made.
CodePudding user response:
The root cause of your problem is a bad source code design (a 'bad smell' as described in https://refactoring.guru/smells/long-method). As a rule of thumb: do not use more than one / two nested conditionals in a function (i.e. while
, if
, until
, ...). Try to refactor your code as e.g. shown in Martin Fowler's Book (https://martinfowler.com/books/refactoring.html) or in many good tutorials (e.g. https://refactoring.guru/extract-method).
You will see that this will simplify your life - and you can use a return
from a function instead of some break statement.