-1

I'm new to Python (I've only used C) and I've discovered new loops such as for/else... So I wonder if I'm ignoring a cleaner way to handle this loop:

flag = 0
for i in range (n):
    if not flag and condition:
        statement_1
        flag = 1
    if flag and condition:
        statement_2

I need to keep the for counting, because I know that at least one element will satisfy the condition, so when I find it I'll do statement_1. Then if another element will satisfy the condition as well, I'll do statement_2.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Domenico Modica
  • 167
  • 1
  • 8
  • 2
    In essence, if the flags and conditions don't really depend on `i` or `n`, then your `if`s are as good as you are going to get. – quamrana May 19 '19 at 20:09
  • I've a list of n positive integers, that can be multiple of 2. It is certain that at least one is not multiple of 2, so firstly I'm looking for it and do statement_1 . (In fact condition_1 is ``list[n]%2``) Then if there's another element not multiple of 2 I have to do statement_2. So the two conditions are identical – Domenico Modica May 19 '19 at 20:42

1 Answers1

0
flag = False  # I prefer booleans
for i in range(n):
    if condition(i):  # We always need it to be True
        if not flag:
            statement(i)
            flag = True
        else:
            statement2(i)

So far this would work, but since you said there is at least one that satisfies the condition

foo = range(n) # any iterable
iterfoo = iter(foo)
initial_value = next(i for i in iterfoo if condition(i))
statement(initial_value)
for i in iterfoo:
    if condition(i):
        statement2(i)

Now these both, (if I'm not missing something) should do the same thing, just in different ways, so it is your choice, although it also saves you 2 lines of code since you wont be doing the first line in your actual code, so I vote for the second snippet :D

Işık Kaplan
  • 2,815
  • 2
  • 13
  • 28