Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip a chunk of code if a condition is True in Python

Tags:

python

I am writing a workflow which contains many steps, say 100. After each step, I want to check if a condition is True, if True, then skip all steps left and go to the "next level". if it goes all the way to the step 100, then go to the "next level" as well.

I can think of using a for loop with 1 iteration

for i in range(1):
    step1()
    if condition:
        break

    step2()
    if condition:
        break
    ...
    step100()

next level()

This seems fine, but is there a better way without the loop and jump to next level directly? It will be helpful if there are again this kind of structures within these steps, and I don't want to break many layers of loops to get to the next level

like image 521
Z Gu Avatar asked Jan 26 '26 05:01

Z Gu


1 Answers

If you really do have 100 steps, that would become a very long unreadable code.

Another option is to pack steps/conditions into lists:

steps = [step1, step2, ... , step100]
conditions = [condition1, condtition2, ...]

for step, condition in zip(steps, conditions):
    step()
    if condition:
        break
next_level()

Of course, if you only have one global condition as in your example, the conditions list is not necessary and you can just loop the steps. The code can also be further reduced in that case to:

steps = [step2, ... , step100]

step1()
while not condition and steps:
    steps.pop(0)()

next_level()
like image 183
Tomerikoo Avatar answered Jan 27 '26 19:01

Tomerikoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!