i have
for i in xrange(repeat):
#does my stuff
time.sleep(10)
BUT, i don’t want it to sleep if it’s the last run. Meaning, if there’s no more iteration, don’t sleep
How do I gracefully handle this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What you seem to want is to do a bunch of things, then sleep between each of them.
Furthermore, the delay is independent of the nature of the tasks.
Solution 1 — Sleep if it isn’t the last
The easiest way is to special-case the for loop:
You could also do the following, but it’s much less elegant because you repeat
doStuff():Solution 2 — While loop with break
One of the most straightforward ways to solve these issues is to break out of a while loop. It’s dirty and somewhat non-functional-programming, but it’s very much how a human might naturally think of the problem:
While loops are annoying because if you make a programming error, your program will infinite-loop.
Solution 3 — Detect if last
The above methods do something if it’s not the first iteration of the loop. However, “detecting the last iteration of the loop” is how you tried to approach the problem. It is a bit more annoying, but you can do it like this: https://stackoverflow.com/a/6090673/711085 and use it like this:
Less elegant is to reverse the list and do
enumerate():(very small irrelevant minutiae: do note that in the
reversed(enumerate(reversed(iterable)))case, if tasks were a generator, it would generate every single task to do, enumerate them in reverse order, then do them: this can cause lag, and also prevents you from creating an infinite task generator)Task abstraction
No matter which way you do it, you may wish to abstract the concept of having tasks by creating callbacks, into which you insert a delay between each, sort of like a
''.join.For reference, if the delay depended on the tasks, then your tasks should return how long to wait.