Home > Mobile >  using break function within the function to stop the further execution of program
using break function within the function to stop the further execution of program

Time:12-01

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

CodePudding user response:

You need to use

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

CodePudding user response:

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

CodePudding user response:

Just for further clarification, the answers above are correct, but the break statement is an 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.)

  • Related