Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Continue in if conditional python loop is not working

a = ['AKDYYDSSGYHFDY', 'AKDDSSGYYFYFDY', 'AKDAGDYYYYGMDV']

match = ['DS', 'DV', 'DY']

counter = 0
for i in a:
    for j in match:
        if j in i:
            print(i, j)
            counter = counter+1
            continue

print(counter)

Results are

AKDYYDSSGYHFDY DS
AKDYYDSSGYHFDY DY
AKDDSSGYYFYFDY DS
AKDDSSGYYFYFDY DY
AKDAGDYYYYGMDV DV
AKDAGDYYYYGMDV DY

6

I was expecting that it would identify the first pattern DS in the first string in list a, then move to next element. However, it proceed to identify DY as well. What am I doing incorrectly? Any help is appreciated.

Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try to replace continue with break like this

a = ['AKDYYDSSGYHFDY', 'AKDDSSGYYFYFDY', 'AKDAGDYYYYGMDV']

match = ['DS', 'DV', 'DY']

counter = 0
for i in a:
    for j in match:
        if j in i:
            print(i, j)
            counter = counter+1
            break

print(counter)

Output:

AKDYYDSSGYHFDY DS
AKDDSSGYYFYFDY DS
AKDAGDYYYYGMDV DV
3

Continue actually means that you go to the next iteration of for loop. Since you have continue inside j loop it doesn’t influence on i loop and simply iterates more on j.

break instead stops iterations on j loop and let’s i loop to proceed on the next iteration

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading