Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Pythonic Way to Run a Process X Times

Tags:

python

loops

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

like image 277
Lionel Avatar asked Nov 24 '10 08:11

Lionel


People also ask

How do you repeat 3 times in Python?

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.

How do you repeat multiple times in Python?

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.

How do you make a Python program repeat itself?

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.


1 Answers

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.

like image 99
Felix Kling Avatar answered Sep 20 '22 22:09

Felix Kling