For and If Loop together - keeping count

How do I keep a count while executing a IF statement within a for loop? I want to execute different code based on the counter. Here is a simplified version of what I'm trying to do:

li = [1,2,3,4,5]

for l in li:
    counter = 1 
    if counter == 1:
        counter +=1
        print(l)
else:
    print('this worked')

Results:

1
2
3
4
5

1 answer

  • answered 2018-01-11 21:11 Usernamenotfound

    If you want the number of times the if condition was hit. Declare the counter variable before the for loop