mercredi 2 septembre 2015

Does an if statement within a loop stop the loop and procedure?

I thought a for-loop would run through all the elements in a list regardless of the conditions of the loop.
For the problem below-I would expect the printed output to be 6,-1,
the last position where p[count]==n and then my return statement after the loop ends.

When if p[count]==n finds a match, does the loop and procedure stop running?
Does someone have a good explanation of how this works?

def find_element(p,n):
    count=0
    for x in p:
        if p[count]==n:
            return count
        count=count+1
    return '-1'

print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')

Aucun commentaire:

Enregistrer un commentaire