Reputation: 207
I've made a short countdown program which starts at 4 and counts down to zero, I'd like this countdown to print each number just once before moving on to the next number (i.e 4,3,2,1,0), but it currently prints each number multiple times.
This is my Code:
import time
def timer():
max_time = 4
start_time = time.time()
while max_time > 0:
difference = time.time() - start_time
if 1 > difference > 0:
print(max_time)
if 2 > difference > 1:
max_time = 3
print(max_time)
elif 3 > difference > 2:
max_time = 2
print(max_time)
elif 4 > difference > 3:
max_time = 1
print(max_time)
elif 5 > difference > 4:
print('Go')
break
timer()
Currently I get a result like this:
4
4
4
4
3
3
3
3
2
2
2
2
1
1
1
1
Where I'd like a result like this:
4
3
2
1
Thanks
Upvotes: 0
Views: 70
Reputation: 4674
To answer your explicit question about a print once type of function: I'd use a class that remembers the last thing printed. It's important to use a context manager (with
expression) here, since the last line printed won't necessarily be garbage collected when you're done with it otherwise.
class Printer:
'''Prints only changed lines'''
def __init__(self):
# a new, unique object() is never equal to anything else
self._last = object()
def __enter__(self):
# let with...as statement get to print_once() directly
return self.print_once
def __exit__(self, *_):
# let the last line be garbage collected
del self._last
def print_once(self, line):
'''Print onlt changed line'''
# don't print the same thing again
if line != self._last:
# print the unique thing
print(line)
# remember the last thing printed
self._last = line
with Printer() as print_once:
for line in [4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1]:
print_once(line)
If, instead, you just want something to count down from 4 once a second, then refer to Tim Roberts' answer. ;)
Upvotes: 0
Reputation: 54645
Your code consumes 100% of a CPU. That's wasteful. You do a timer by putting yourself to sleep for a while:
import time
def timer():
max_time = 4
for i in range(max_time,0,-1):
print(i)
time.sleep(1)
print('Go')
timer()
Upvotes: 1