-3

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
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187

1 Answers1

0

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

Usernamenotfound
  • 1,469
  • 2
  • 10
  • 17