Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do you go about starting the next i without using continue or break?

def function_in_main():
    if #something happens:
        #start new next iteration for the loop in the main function

def main():
    n = 1
    for i in range(len(alist)): 
        print ('step ', n)

        function_in_main()

        n += 1
main()

Output should look somewhat like:

step 1

#if or until something happens

step 2

etc

share|improve this question
    
Should the loop break if the condition something happens is not met? –  Hyperboreus Apr 7 at 19:59
    
@Hyperboreus no it shouldn't –  user3323799 Apr 7 at 20:02
    
Let me rephrase: What should happen if the condition something happens is not met? –  Hyperboreus Apr 7 at 20:11

4 Answers 4

Just make function_in_main return when your if statement is true. when it returns, the loop will move on to the next iteration and then re-call function_in_main.

share|improve this answer

Maybe try raising an exception:

def function_in_main():
    if #something happens:
        raise Exception

def main():
    n = 1
    for i in range(len(alist)): 
        print ('step ', n)
        try:
            x()
        except Exception:
            continue

        n += 1
main()

You can specify or make whatever type of exception you want.

share|improve this answer

Here is an example:

def function_in_main(x):
    return x=='Whopee'         # will return True if equal else False

def main():
    alist=['1','ready','Whopee']
    for i,item in enumerate(alist, 1): 
        print ('step {}, item: "{}" and {}'.format(i,item,function_in_main(item)))     

main()

Prints:

step 1, item: "1" and False
step 2, item: "ready" and False
step 3, item: "Whopee" and True

Note the use of enumerate rather than manually keeping a counter.

share|improve this answer

Sure you're not thinking of a while loop or something? It's a little tough to see what you're getting at…

def your_function():
    #…do some work, do something to something else
    if something_is_true:
        return True
    else:
        return False

def main():
    condition = True
    for i in range(len(your_list)):
        while condition:
            print "Step: %d" % i
            your_function()

Only when your_function returns False will the loop in main continue, otherwise it will stay within the while loop.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.