Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue after the return command in python?

Tags:

python

Imagine we have a piece of code which cuts the large data into smaller data and do some process on it.

def node_cut(input_file):
    NODE_LENGTH = 500
    count_output = 0
    node_list=[]

    for line in input_file.readlines():
        if len(node_list) >= NODE_LENGTH :
            count_output += 1   
            return( node_list,count_output )
            node_list=[]  

        node,t=line.split(',')
        node_list.append(node) 

if __name__ =='__main__':

    input_data = open('all_nodes.txt','r')
    node_list, count_output = node_cut(input_data)
    some_process(node_list)

while node_cut return the first data list, the for loop stop going on for the rest of the large data. How I can make sure that it returns but still the loop continues?

like image 531
masti Avatar asked Oct 25 '11 10:10

masti


People also ask

Can you continue a function after return?

No. But yes. No line of the function will be executed after the return statement. However, the return statement also marks the end of the function and therefor the end of the scope.

Does function continue after return Python?

No, a return gives the value back to the caller and stops. And then code the caller to expect a pair of (response, task) , rather than just a response.

Can you break after return Python?

No, it doesn't work like that unfortunately. You would have to check the return value and then decide to break out of the loop in the caller. Show activity on this post.


1 Answers

Use yield:

def node_cut(input_file):
    NODE_LENGTH = 500
    count_output = 0
    node_list=[]

    for line in input_file.readlines():
        if len(node_list) >= NODE_LENGTH :
            count_output += 1   
            yield( node_list,count_output )
            node_list=[]  

        node,t=line.split(',')
        node_list.append(node) 

if __name__ =='__main__':
    with open('all_nodes.txt','r') as input_data:
      for node_list, count_output in node_cut(input_data):
        some_process(node_list)
like image 118
NPE Avatar answered Sep 22 '22 14:09

NPE