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 else: raise StopIteration iter_ = Iterator(0.1) for i in iter_: print(i)
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