Chris Cris
Chris Cris

Reputation: 215

Transform a while loop with counter into a more pythonic code

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

Answers (3)

jeromej
jeromej

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

itzMEonTV
itzMEonTV

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

lain
lain

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

Related Questions