Here is my goal: To make a small program (text based) that will start with a greeting, print out a timer for how long it has been since the last event, and then a timer for the
Ok, I'll start with why your timer is lagging.
What happens in your program is that the time.sleep()
call "sleeps" the program's operation for 1 second, once that second has elapsed your program begins execution again. But your program still needs time to execute all the other commands you've told it to do, so it takes 1s + Xs
to actually perform all the operations. Although this is a very basic explanation, it's fundamentally why your timer isn't synchronous.
As for why you're constantly printing on a new line, the print()
function has a pre-defined end of line character that it appends to any string it is given.
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
You can overwrite this with anything by putting end="YourThing"
in your print statement like so
for x in range(3):
print("Test", end="")
The above example appends an empty string to the end of the line, so the output of the loop would be
"TestTestTest"
As for solving your timer problem, you should use something similar to
timePoint = time.time()
while True:
#Convert time in seconds to a gmtime struct
currentTime = time.gmtime(time.time() - timePoint))
#Convert the gmtime struct to a string
timeStr = time.strftime("%M minutes, %S seconds", currentTime)
#Print the time string
print(timeStr, end="")