[Tutor] While loop counter
Alan Gauld
alan.gauld at btinternet.com
Tue Jul 8 02:24:26 CEST 2008
"David" <david at abbottdavid.com> wrote
> Hi, I am trying to get a while loop that will execute 5 time then
> stop.
Copngratulations, you have succeeded.
Unfortunately nothing happens inside your loop. I suspect you
actually want to execute some code 5 times?
> #counter = 0
> #while counter < 5 :
> # counter = counter + 1
Yep, this would have done it.
> while True:
> mytime.tick()
> mytime.print_time()
> time.sleep(1) # Sleep for 1 second
And this loop runs forever because you never break
out of it.
> counter = 0
> while counter < 5 :
> counter = counter + 1
If you did get out of the infinite loop above then this one does do
it too.
But all it does is increment the counter. If you want code to be
executed
it must also be inside the loop (ie inside the indented code section).
So what I think you wanted would be:
counter = 0
while counter < 5:
mytime.tick()
mytime.print_time()
time.sleep(1) # Sleep for 1 second
counter = counter + 1
But since its for a fixed number of iterations you are better
off using a for loop:
for counter in range(5)
mytime.tick()
mytime.print_time()
time.sleep(1) # Sleep for 1 second
Note we don't need to increment the counter in this version.
See the loops section of my tutorial for more about for
and while loops.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list