Reputation: 465
while True:
now = datetime.datetime.now()
if now.second == 1:
print "One"
my program print One about 7 times. How do I make it print only once?
Upvotes: 0
Views: 1443
Reputation: 31633
How about storing the value previously used for printing?
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
Upvotes: 0
Reputation: 212835
Your computer is too fast.
It takes the current time, tests whether the current second is one and then again. And since it is so fast it can do this within less than one second, you get more lines of output.
Make it wait after each iteration:
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
This program will sleep most time. If you want it to do anything useful, it will be a different program.
Upvotes: 2