python

Condition in a function to stop it when called in a loop?


Please consider this simple function:

def my_func(x):
    if x > 5:
        print(x)
    else:
        quit()

    print('this should be printed only if x > 5')

Then if we call this function in a loop:

for i in [2, 3, 4, 5, 6, 7]:
    my_func(i)

Expected output:

6
this should be printed only if x > 5
7
this should be printed only if x > 5

But quit actually disconnects the Kernel.

I know that the following function will work but I do not want to have the second print up there:

def my_func(x):
    if x > 5: 
        print(x)
        print('this should be printed only if x > 5')
    else:
        pass

Lastly, I know that if I put the loop inside the function, I can use continue or break but I prefer to keep the function simple and instead put the function call in a loop. So, what needs to change in the first function to achieve the expected output?


Solution

  • Indeed, quit() will quit the application. If what you want is to return from the function, return does exactly that:

    def my_func(x):
        if x > 5: print(x)
        else: return
    
        print('this should be printed only if x > 5')
    
    for i in [2, 3, 4, 5, 6, 7]:
        my_func(i)
    

    This has nothing to do with loops. return simply ends execution of the function and returns control to where the function was called. If that control happens to be in a loop then control is now back in a loop.