Reputation: 215
Is there a way to trasform this python code into a more pythonic one?
i = 0
while condition:
doSomething()
i+=1
Upvotes: 2
Views: 154
Reputation: 11588
To second itzmeontv's answer, I personally do this:
for i in itertools.count():
if not condition:
break
do_something()
Note: Infinite loops are usually to be avoided if possible but, you know what's worse? Manual counters. Especially if they are at the bottom of the loop. That's why I put the condition check at the very top, right under the for
loop statement.
However, if you know how many iterations you need, you can just use:
for i in range(100):
do_something()
And replace 100
by the desired amount of iterations.
Upvotes: 0
Reputation: 20349
I use count
for this type.
from itertools import count
c = count(0)
while condition:
doSomething()
next(c) # returns 0, +1 in further loops
But if you know how much loops you want, Try for loop
.
for i in range(n):
doSomething()
Upvotes: 1
Reputation: 448
If the condition is about the value of i like "i < 10", you can use "for" statement:
for i in range (10):
do_something ()
This will execute the function 10 times.
Upvotes: 1