【问题标题】:using break function within the function to stop the further execution of program在函数中使用 break 函数来停止程序的进一步执行
【发布时间】:2022-12-01 16:13:20
【问题描述】:
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
         

如果如果条件满足。

这是这样做的正确方法吗..?因为 break 只结束循环,但我想结束函数

【问题讨论】:

  • 你想一起停止功能或程序吗?

标签: python dataframe


【解决方案1】:

你需要使用

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

【讨论】:

    【解决方案2】:

    您可以将 break 替换为 return,只需使用 return 即可帮助您转义函数,这将中断函数的进一步执行。

    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
    

    【讨论】:

      【解决方案3】:

      只是为了进一步澄清,上面的答案是正确的,但是 break 语句用于循环,如 for 循环或 while 循环以提前结束循环。

      另一方面,函数要么在最后一行结束,要么在调用 return 时结束。如果没有参数传递给return,该函数默认返回None。 (如果根本没有调用return语句,默认情况下也会返回None。)

      【讨论】:

        猜你喜欢
        • 2021-04-22
        • 2014-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        • 2019-03-24
        相关资源
        最近更新 更多