Z Gu
Z Gu

Reputation: 163

Skip a chunk of code if a condition is True in 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

Upvotes: 3

Views: 5427

Answers (3)

Tomerikoo
Tomerikoo

Reputation: 19440

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()

Upvotes: 12

Giannis Clipper
Giannis Clipper

Reputation: 707

I suggest an idea based to OR operator (statements executed until first is True). Here is an example:

import random

def step1(val):
    print('step1...')
    return val%3
def step2(val):
    print('step2...')
    return val%3
def step3(val):
    print('step3...')
    return val%3
def step4(val):
    print('step4...')
    return val%3
def step5(val):
    print('step5...')
    return val%3
def step6(val):
    print('step6...')
    return val%3
def step7(val):
    print('step7...')
    return val%3
def step8(val):
    print('step8...')
    return val%3
def step19(val):
    print('step9...')
    return val%3
def step10(val):
    print('step10...')
    return val%3
def next_level():
    print('next_level...')
    return

def ok(func):
    result = func(random.randint(1, 30))
    if result == 0:
        return True
    else:
        return False

if ok(step1) or ok(step2) or ok(step3) or ok(step4) or ok(step5)\
    or ok(step6) or ok(step7) or ok(step8) or ok(step9) or ok(step10)\
    or True:

    next_level()

Upvotes: 0

jimsu2012
jimsu2012

Reputation: 170

A function can accomplish that:

def workflow():
    step1()
    if condition:
        return

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

workflow()
next_level()

Upvotes: -2

Related Questions