Timer/Countdown Tutorial in Python
Timer and Countdown Tutorial
This tutorial is going to help teach you how to implement a timer and a countdown with code.
How to Use a Timer with Code
The first thing that you will learn in this tutorial is how to use a timer during a game or something like that.
First of all, you need to start with this code:
starting_time = time.time()
Of course, you will need to
import time for the code to work because we are using this module. Anyway, for more explanation with this line of code above, basically it will get the time. This time will be used later when the timer is stopped.
After using that code, you can write any code for your repl that you want the user to be timed of such as guessing a number or finishing a quiz question.
After finishing writing the code in between, the final part is to add this line of code.
end_time = time.time()
This is important because it helps get the time of when you are finished. Now, you probably want to show the user what their time was for finishing a certain game or quiz. Here is how you would implement this code:
print(end_time - start_time)
However, I suggest you use the round method because there are a lot of number after the decimal point. The way you would do it is:
print(round(end_time - start_time, number)
For that number part, replace the number with the number of decimal places you want to show the user.
Congratulations! You were able to make a timer!
How to Make a Countdown Using Code
The second part of this tutorial is how to implement code for a countdown. This is kind of the same with the code for a time but not really.
Again, you will need import time for this.
Here is how to make a countdown with the following code:
starting_time = time.time() ending_time = time.time() while ending_time - starting_time < number: ending_time = time.time() print(round(number - (ending_time - starting_time), number1))
Basically, what this code does is that it will use starting_time and ending_time to check the time. However, ending_time always changes which will make the while loop not infinite. You must replace the number with the number of seconds you want the countdown to be. For the print statement instead of just subtracting starting_time from ending_time, you have to put the number of seconds you want the countdown to be so that the number slowly decreases. For the number1 variable, you must replace it with the number of digits after the decimal points to display with the user.
Congratulations, you know how to create a countdown.
However, you must note that this method for countdown will not work if you use inputs or the getkeys.
This is the end of the tutorial.
Please upvote if this tutorial helped you with coding and comment down below for any suggestions to make this tutorial better.
Thanks and have a nice day.