Which is more pythonic?
While loop:
count = 0 while count < 50: print "Some thing" count = count + 1
For loop:
for i in range(50): print "Some thing"
Edit: not duplicate because this has answers to determine which is clearer, vs. how to run a range without 'i' -- even though that ended up being the most elegant
The Python for statement iterates over the members of a sequence in order, executing the block each time. Contrast the for statement with the ''while'' loop, used when a condition needs to be checked each iteration or to repeat a block of code forever. For example: For loop from 0 to 2, therefore running 3 times.
In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.
We can loop back to the start by using a control flow statement, i.e., a while statement. To do that, wrap the complete program in a while loop that is always True. What is this? Moreover, add a continue statement at a point where you want to start the program from the beginning.
Personally:
for _ in range(50): print "Some thing"
if you don't need i
. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange
as there is no need to generate the whole list beforehand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With