for loop with a condition depending on a variable


How to implement a for loop in Python with a condition like in С

for (int val = 1; ((double) 4 / val) > e; val = val + 2)

I tried to do such a loop through iterators, but as for me, this solution is too cumbersome

class Iterator:
    def __iter__(self):
        return self
    def __init__(self, e):
        self.e = e
        self.val = 1
    def __next__(self):
        if 4 / self.val > self.e:
            self.val += 2
            return self.val
            raise StopIteration
iter_ = Iterator(0.1)
for i in iter_:

Is there any simpler analogue, or in such cases the only option is to use a while cycle?


You could also just transform the loop condition.

4 / val > e is mathematically equivalent to
4 / e > val unless val or e are 0.

So then that becomes val < 4/e and now we just have:

bound = math.ceil(4/e)
for val in range(1, bound, 2):
  # do some other stuff

Answered By – Lagerbaer

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published