Countdown
Creating a timer in python
import time
def countdown(sec):
print(sec + " seconds remaining")
time.sleep(1)
countdown("10")
countdown("9")
countdown("8")
countdown("7")
countdown("6")
countdown("5")
countdown("4")
countdown("3")
countdown("2")
countdown("1")
countdown("0")
print("Time's up!")
Using a list
I realized as I was making the code that this is something which could be done by abstracting data. I did not want to type the whole list myself, so I found code on the internet which can create a list with any numbers you want. I chose 0-60 as that made the most sense, regarding the timer is only in seconds. You can make the list as big as you want though.
def create_list(r1, r2):
if r1 == r2:
return r1
else:
res = []
while (r1 < r2+1 ):
res.append(r1)
r1 += 1
return res
# create list of number 0-60 for one minute
r1, r2 = 0, 60
print(create_list(r1, r2))
I then turned this list created into a defined list in my code:
seconds = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60"]
print(seconds)
Here is the code for the actual program I created. I realized along the way that it would be really cool if you could choose how long you wanted the timer be instead of just having it a minute long. Using what I learned about loops recently, I realized a while loop can create the function I wanted. However, I ran into multiple problems such as the list counting backwards and the loop never stopping, but after changing parts and a couple internet searches I figured out how to make it work the way I wanted to. You can input any number from 0-60 and it will give you a timer of that long.
def timer():
time_wanted = int(input("How many seconds do you need?"))
while time_wanted < len(seconds):
record = seconds[time_wanted]
countdown(record)
time_wanted -= 1
if time_wanted == -1:
break
return
timer()
print("Time's up!")