Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading