函数不断返回无

时间:2016-03-29 13:06:40

标签: python nonetype

我试图编写一个函数来计算输入文件中有多少行以' AJ000012.1'但我的功能一直没有返回。我是一个初学者,并不完全确定问题是什么以及为什么会这样。答案应该是13,当我只编写代码时,例如:

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

我得到了正确的答案。当我尝试将其作为一个函数并调用它时,它不起作用:

    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))

任何帮助都会受到重视,谢谢!

(如果你想知道,HSP代表高得分段对。输入文件是列出DNA序列比对结果的BLAST报告文件)

1 个答案:

答案 0 :(得分:5)

如果您只是return而未指定要返回的内容,则不会返回任何内容。它将是None。您想要返回某些内容。根据您的规范,您希望返回count。此外,您将在for循环中返回,这意味着您永远不会得到您期望的计数。您想要计算所有匹配项,因此您需要将此返回值移出循环:

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