[Tutor] Repeating an action

Andre Engels andreengels at gmail.com
Sat May 12 16:57:21 CEST 2007


2007/5/12, Alan Gilfoy <agilfoy at frontiernet.net>:
> How do you 'tell' Python to repeat a certain action X amount of times,
> and then stop.
>
> I could use a 'counter' (see below), but that seems kind of clunky.
>
>
>
> counter = 0
> example = True
> while example:
>
>      print "Do something"
>      counter += 1
>
>      if counter == 100:
>      example = False

You can use a for loop:

for i in range(100):
    print "Do something"

Your own code is unnecessary wordy too, by the way. The same thing can
be done with:

counter = 0
while counter < 100:
    print "Do something"
    counter += 1

but of course the 'for' solution is still shorter than this.

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels


More information about the Tutor mailing list