简体   繁体   中英

How can I use a for loop as a timer?

Is there any way to use a for loop as a timer? I've tried this:

a = 0
for i in range(1, 10000):
    a += 1

print "Hello World"

But for some reason, it immediately cuts to "Hello World." I thought that Python incremented every tick or 1/1000th of a second. If so, than 10000/1000 = 10, so that for loop should last for 10 seconds right? If someone could help me understand this, I'd appreciate it a lot.

The range function returns a list of numbers in Python 2.x (or an iterator, in Python 3.x) in the given range. It has nothing, nothing to do with time, or ticks as you incorrectly assumed. The a += 1 statement will execute immediately and as many times as defined by the range - which will be very quick in a modern computer.

In general, any instruction in any high level programming language will be executed as fast as the hardware permits, there isn't an implicit timer that dictates that an instruction executes for each tick of the processor - think of it, it'd be terrible for performance! If you need to pause the execution of a program for 10 seconds, don't use a loop for implementing a delay, instead use the sleep function for suspending the execution during a given number of seconds:

import time
# some code before
time.sleep(10) # sleep for 10 seconds
# some code after

您是否尝试过time.sleep(<number of seconds you want it to wait>)

Don't do that, as the execution time will depend on a lot of factors!

Try the sleep method instead:

time.sleep(10)

Use the Sleep method to achieve that result.

time.sleep(X)

Where X is the number of seconds you want it to pause.

Using your piece of code, you can try to put time.sleep(1) inside the for loop. However, Racso and Edgar have told you a better way to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM