pythonbeginner2506
pythonbeginner2506

Reputation: 49

Function keeps returning None

I'm trying to write a function to count how many lines in my input file begin with 'AJ000012.1' but my function keeps returning None. I'm a beginner and not entirely sure what the problem is and why this keeps happening. The answer is supposed to be 13 and when I just write code eg:

    count=0
    input=BLASTreport
    for line in input:
    if line.startswith('AJ000012.1'):
        count=count+1
    print('Number of HSPs: {}'.format(count))

I get the right answer. When I try to make this a function and call it, it does not work:

    def nohsps(input):
        count=0
        for line in input:
            if line.startswith('AJ000012.1'):
            count=count+1
            return

    ans1=nohsps(BLASTreport)
    print('Number of HSPs: {}'.format(ans1))

Any help would be seriously appreciated, thank you!

(HSP stands for high scoring segment pair if you're wondering. The input file is a BLAST report file that lists alignment results for a DNA sequence)

Upvotes: 2

Views: 90

Answers (1)

idjaw
idjaw

Reputation: 26578

When you simply return without specifying what you are returning, you will not return anything. It will be None. You want to return something. Based on your specifications, you want to return count. Furthermore, you are returning inside your for loop, which means you are never going to get the count you expect. You want to count all occurrences of your match, so you need to move this return outside of your loop:

def nohsps(input):
    count=0
    for line in input:
        if line.startswith('AJ000012.1'):
        count=count+1
    return count

Upvotes: 5

Related Questions