Re: function return

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fredrik Lundh

    Re: function return

    Beema Shafreen wrote:
    I have a script using functions , I have a problem in returning the
    result. My script returns only one line , i donot know where the looping
    is giving problem, Can any one suggest, why this is happening and let me
    know how to return all the lines
    >
    def get_ptm():
    fh = open('file.txt' , 'r')
    data_lis = []
    for line in fh.readlines():
    data = line.strip().sp lit('\t')
    id = data[0].strip()
    gene_symbol = data[1].strip()
    ptms = data[8].strip()
    result = "%s\t%s\t%s " %(id,gene_symbo l,ptms)
    return result
    note that you put the "return" statement inside the loop, so returning
    only one line is the expected behaviour.

    result = "%s\t%s\t%s " %(id,gene_symbo l,ptms)
    data_lis.append (result)

    and then return the list when done:
    fh.close()
    return data_lis

    :::

    if you change the original return to "yield", the function will turn
    into a "generator" that yields one result at a time.

    result = "%s\t%s\t%s " %(id,gene_symbo l,ptms)
    yield result

    for more on generators, and how they are used, see the documentation.

    </F>

Working...