Biopython Failure to break out of loop After qblast, I wanted to print only details from the first 3 BLAST output. Yet, the code below printed the details of every BLAST output. Why can't I break out of the loop to achieve my desired output?

for alignment in blast_records.alignments:
    countResults = 0
    for hsp in alignment.hsps:  
        if countResults == maxResults:
            countResults = 0
        break
        else:
            print(alignment.title)
            print(alignment.length/ len(seq)*100)
            print(hsp.expect)
            print(hsp.identities)
            countResults += 1
Assuming that your actual code is this:

for alignment in blast_records.alignments:
    countResults = 0
    for hsp in alignment.hsps:  
        if countResults == maxResults:
            countResults = 0
            break
        else:
            print(alignment.title)
            print(alignment.length/ len(seq)*100)
            print(hsp.expect)
            print(hsp.identities)
            countResults += 1


Here you have an outer loop, which is iterating over all the possible database matches, and an inner loop, iterating over the alignments within that database entry. You are currently limiting the inner loop, but not the outer loop, which you probably want to do. Try this:

# Take the first 3 database hits
for alignment in blast_records.alignments[:3]:
    for hsp in alignment.hsps:  
            print(alignment.title)
            print(alignment.length/ len(seq)*100)
            print(hsp.expect)
            print(hsp.identities)