using break function within the function to stop the further execution of program

Question:

def my_function(df_1) :
         
         df_1 = df_1.filter[['col_1','col_2','col_3']]
         
         # Keeping only those records where col_1 == 'success'
         df_1 = df_1[df_1['col_1'] == 'success']
         
         # Checking if the df_1 shape is 0
         if df_1.shape[0]==0:
             print('No records found')
             break

        #further program
         

I am looking to break the execution of further program if the if condition is met.

is this the correct way to do so..? since break only ends the loop, but i want to end the function

Asked By: Roshankumar

||

Answers:

You need to use

 if df_1.shape[0]==0:
         print('No records found')
         return 
Answered By: kingrazer

You can replace break with return just using return will help you escape the function which will break the further execution of the function.

def my_function(df_1) :
     
     df_1 = df_1.filter[['col_1','col_2','col_3']]
     
     # Keeping only those records where col_1 == 'success'
     df_1 = df_1[df_1['col_1'] == 'success']
     
     # Checking if the df_1 shape is 0
     if df_1.shape[0]==0:
         print('No records found')
         return

    #further program
Answered By: Jeson Pun

Just for further clarification, the answers above are correct, but the break statement is used in loops like a for loop or while loop to end the loop prematurely.

Functions on the other hand end either at the last line or when return is called. If no agument is passed to return, the function returns None by default. (None is also returned by default if the return statement is not called at all.)

Answered By: ljbkusters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.