Python 2.7 While 循环时间
while True:
now = datetime.datetime.now()
if now.second == 1:
print "One"
我的程序打印了大约7次“One”。我该怎么做才能让它只打印一次呢?
2 个回答
0
之前用来打印的值怎么存起来呢?
previous = None
while True:
now = datetime.datetime.now()
if now.second == 1 and now.second != previous:
print "One"
previous = now.second # store the last value
2
你的电脑速度太快了。
它会获取当前时间,检查现在的秒数是否为1,然后再检查一次。因为它的速度非常快,所以在不到一秒的时间内就能完成这些操作,这样你就会看到更多的输出内容。
让它在每次循环后等一等:
while True:
now = datetime.datetime.now()
if now.second == 1:
print "One"
time.sleep(59) # wait 59 seconds after success
time.sleep(1) # wait 1 second after each fail
这个程序大部分时间都会在“睡觉”。如果你想让它做一些有用的事情,那就需要写一个不同的程序。