The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 Skip A Chunk Of Code If A Condition Is True In Python
00:43 Accepted Answer Score 12
01:15 Answer 2 Score 0
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/5983...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 12


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



ANSWER 2

Score 0


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