The Python Oracle

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

This video explains
Skip a chunk of code if a condition is True in Python

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

Music by Eric Matyas
https://www.soundimage.org

Track title: Puzzle Game 2 Looping

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

--

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

--

Chapters
00:00 Question
00:57 Accepted answer
01:39 Answer 2
02:29 Answer 3
02:44 Thank you

--

Tags
#python



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