Making a Timer in Python 3 - python

So, I'm trying to make a countdown timer in Python. However, I am finding difficulty trying to replace the current printed number with the next lowest number. So, for example, 30 would be printed, then the number 29 would replace it, and then 28 would replace it and so on.
def timer():
# I haven't made the counting down yet(sorry)
for i in range(30):
print(i, end = '\r')
If anyone could help me that would be great.

You must use the range function with all its parameters.
range(start, stop[, step])
This is a versatile function to create
lists containing arithmetic progressions. It is most often used in for
loops. The arguments must be plain integers. If the step argument is
omitted, it defaults to 1. If the start argument is omitted, it
defaults to 0. The full form returns a list of plain integers [start,
start + step, start + 2 * step, ...]. If step is positive, the last
element is the largest start + i * step less than stop; if step is
negative, the last element is the smallest start + i * step greater
than stop. step must not be zero (or else ValueError is raised)
If you want to replace a good option is to use the carriage return: "\ r" and change the print end "\n" to ""
import time
for x in range(30, 0, -1):
print("\r %d" % x, end="")
time.sleep(1)

With your question title I think you want countdown timer, so here is my code to help you. Maybe this is your question's answer:
import time
hour = int(input('Enter any amount of hours you want -+==> '))
minute = int(input('Enter any amount of minutes you want -+==> '))
second = int(input('Enter any amount of seconds you want -+==> '))
time = hour*10800 + minute*3600 + second*60
print('{}:{}:{}'.format(hour,minute,second))
while time > 0:
time = time - 1
seconds = (time // 60) % 60
minutes = (time // 3600)
hours = (time // 10800)
print('Time Left -+==> ',hours,':',minutes,':',seconds,)
if time == 0:
print('Time Is Over!')
EDIT:
import os # For screen clear command
import time # For timer
hour = int(input('Enter any amount of hours you want -+==> '))
minute = int(input('Enter any amount of minutes you want -+==> '))
second = int(input('Enter any amount of seconds you want -+==> '))
time = hour*10800 + minute*3600 + second*60
print('{}:{}:{}'.format(hour,minute,second))
while time > 0:
os.system("{}") # Replace "{}" as "CLS" for windows or "CLEAR" for other.
time = time - 1
seconds = (time // 60) % 60
minutes = (time // 3600)
hours = (time // 10800)
print('Time Left -+==> ',hours,':',minutes,':',seconds,)
if time == 0:
os.system("{}") # Replace "{}" as "CLS" for windows or "CLEAR" for other.
print('Time Is Over!')

Well this is actually a good solution. It works as well and it is very simple.
First, import some modules
import os
import time
Now I recommend you create a function called whatever you like. I put timer. Then enter this code, you can rename the variable.
def timer(self):
while self != 0:
print(self)
time.sleep(1)
os.system('clear')
self = self - 1
This is pretty simple as well and doesn't require a bunch of lines of code

Related

How do I stop a separate function from running after my countdown timer function ends?

I'm a complete beginner in programming and just wanted to code something I thought was interesting in python. I want to code the rest of it myself, but I got stumped on this part and cannot figure it out at all.
This is my code so far...
block, is the name I gave each session where users can input numbers
there are 3 blocks where users are given 5 seconds of time in each block
to enter (as many sequences of "5" numbers) as they can.
each time the user enters a sequence of numbers, it should add those values to an index in the block_list. (doesn't matter if they enter 3 or 8 values)
Here's the problem:
So after entering some numbers in, as soon as the timer runs out, I want the program to submit whatever the user is inputting to the list and skip to the next block iteration.
My code just doesn't do this and it also is stuck in a loop as well
Looking for help thanks!
Here is the output:
OUTPUT
and here is the code:
from threading import Thread
import time
from random import *
block = 0
def main():
global block
while block < 3:
Thread(target=userInputs).start()
Thread(target=countTime(5)).start()
block += 1
block_list = []
timeOut = True
def userInputs():
while timeOut == True:
num_inputs = int(input("Input 5 numbers and then press 'enter': "))
block_list.append(num_inputs)
print(block_list)
start_time = time.time()
num_list = [1,2,3,4]
block_list = []
def countTime(seconds):
global timeOut
global start_time
while True:
elapsed_time = time.time() - start_time
if elapsed_time >= seconds:
print()
print("Time spent:")
print(time.time()-start_time)
timeOut = False
break
timeOut = True
start_time = time.time()
print(start_time)
main()

Doubling amount per day, need to convert number of pennies to dollars + cents

This program starts with 1 cent and doubles each day. However, I'm stuck on trying to find a way to convert the number of pennies into a dollar and cent amount. For example, converting 1020 pennies to $10.20.
I'm also attempting to make it so if user input is not a positive number, the user will be continously prompted until they enter a positive number. This isn't working, however.
I also feel I've messed up by using range, as I want to enter a set number of days, say 16 days, and when I enter 16, I receive the days 1-17, as range should be doing, and I'm not sure how to go about fixing that.
b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))
print("Day 1:","1")
days = 1
aIncrement = 2
penny = 1
for i in range(b):
pAmount = int(penny*2)
addAmount = int(2**aIncrement -1)
aIncrement +=1
days +=1
penny *= 2
print("Day " + str(days) + ":",pAmount)
Your question has multiple parts, which is not ideal for stackoverflow, but I will try to hit them all.
Fixing the numeric values to show dollars and cents.
As noted in comments to other answers, division can often run into snags due to floating point notation. But in this case, since all we really care about is the number of times 100 will go into the penny count and the remainder, we can probably safely get away with using divmod() which is included with Python and calculates the number of times a number is divisible in another number and the remainder in whole numbers.
For clarity, divmod() returns a tuple and in the sample below, I unpack the two values stored in the tuple and assign each individual value to one of two variables: dollars and cents.
dollars, cents = divmod(pAmount, 100) # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents) # create a string from
# each int
Fixing the range issue
The range() function produces a number and you can set it to start and end where you want, keeping in mind that the ending number must be set at one value higher than you want to go to... i.e. to get the numbers from one to ten, you must use a range of 1 to 11. In your code, you use i as a placeholder and you separately use days to keep track of the value of the current day. Since your user will tell you that they want b days, you would need to increment that value immediately. I suggest combining these to simplify things and potentially using slightly more self-documenting variable names. An additional note since this starts off on day one, we can remove some of the setup code that we were using to manually process day one before the loop started (more on that in a later section).
days = int(input("Input number of days "))
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day
Continuous input
If we ask the user for an initial input, they can put in:
a negative number
a zero
a positive number
So our while loop should check for any condition that is not positive (i.e. days <= 0). If the first request is a positive number, then the while loop is effectively skipped entirely and the script continues, otherwise it keeps asking for additional inputs. Notice... I edited the string in the second input() function to show the user both the problem and to tell them what to do next.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))
Putting all this together, the code might look something like this:
I put the items above together AND cleaned up a few additional things.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2 # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny) # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1) # this line not needed
# aIncrement +=1 # this line not needed
penny *= 2
print("Day " + str(day) + ":", output)
For the continuous prompting, you can use a while loop.
while True:
user_input = int(input("Enter the number"))
if user_input > 0:
break
else:
continue
Or alternatively:
user_input = int(input("Enter the number"))
while user_input <= 0:
user_input = int(input("Enter the number"))
For the range issue, you can add -1 to the parameter you're passing range.
for i in range(b - 1):

Python, how do I make a countdown clock that asks the user what number they want to start at

Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong
count = int(input("What number do you want the timer to start: "))
count == ">" -1:
print("count")
print("")
count = count - 1
time.sleep(1)
You need to ensure you import the time library before you can access the time.sleep method.
Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression.
IF <Expression> is TRUE:
DO THIS.
Also consider using a range within your for loop see below;
import time
count = int(input("What number do you want the timer to start: "))
for countdown in range(count,0,-1):
print (countdown)
time.sleep(1)
Explanation;
for countdown in range(count,0,-1):
range (starting point, end point, step) . Starts at your given integer, ends at 0, steps by -1 every iteration.
In the 2nd line, you can't deduct 1 from ">" which is a string.
What you need here is apparently a for loop. EDIT: You forgot the import too!
import time
count = int(input("What number do you want the timer to start: "))
for i in range(count):
print("count")
print(i)
count = count - 1
time.sleep(1)
The syntax error presumably comes from the line that reads
count == ">" -1:
I'm not sure where you got that from! What you need is a loop that stops when the counter runs out, and otherwise repeats the same code.
count = int(input("What number do you want the timer to start: "))
while count > 0:
print("count", count)
print("")
count = count - 1
time.sleep(1)
You could also replace count = count -1 with count -= 1 but that won't make any difference to the operation of the code.
First, you must import time in order to use the time.sleep() function
Next, I'm not too sure what you mean by:
count == ">" -1:
If you're creating a "stopwatch", then it would be logical to use some sort of a loop:
while count > 0:
print(count,"seconds left")
count -= 1
time.sleep(1)
print ("Finished")
That should work fine.
There is a syntax error in your second line. I am not sure what you are trying to achieve there. Probably you want to check if count>-1.
do this:
import time
count = int(input("What number do you want the timer to start: "))
if count>0:
while(count):
print(count)
time.sleep(1)
count = count -1

Trouble with a Python Countdown Program

I have recently finished a course in Python about a month ago. I am continuing expanding my knowledge on Python by creating programs.
The code below is a program for a Python countdown program. What the program does is that it asks the user to input a count of seconds, minutes, and hours.
Anyways, I noticed 2 Bugs that occur in the program.
First Bug:
If we enter an hour and second count (and no minute count), the program would count the remaining time for that certain hour, but it would not subtract the hour and set the minute back to 59. Instead, it would print the minute as a negative number.
Second Bug:
If we enter an hour, second, and minute count, the program would count the reamaining time. But when the program reaches the very last minute (i.e. 01:00:59), it would skip that minute and go on to the next one (i.e. 00:59:59).
About the 2nd Bug: Suppose I enter 1 Hour, 1 Minute, 5 Seconds. It would count down the 5 Seconds. The computer would then print 1:00:00. Instead of counting down the seconds for that certain minute. It would skip to 0:59:59. Hope that helps
It would be fantastic if I could receive some assistance with fixing these two bugs, and maybe a way to differently format the program.
Thanks for reading and I am looking forward to your answer,
-Anonymous
import time
time_count = 0
second = int(raw_input("Seconds:"))
count_minute = int(raw_input("Minutes:"))
count_hour = int(raw_input("Hours:"))
time_count += second
time_count += count_minute * 60
time_count += count_hour * 3600
def clean():
global second
global count_minute
global count_hour
print_second = str(second).zfill(2)
print_minute = str(count_minute).zfill(2)
print_hour = str(count_hour).zfill(2)
print "%s:%s:%s" % (print_hour, print_minute, print_second)
time.sleep(1)
clean()
time.sleep(1)
for i in range(1, time_count + 1)[::-1]:
if second == 0 and count_minute == 0 and count_hour == 0:
clean()
break
elif second != 0:
second -= 1
elif second == 0:
count_minute -= 1
second = 59
if count_minute == 0 and count_hour > 0:
clean()
count_hour -= 1
count_minute = 59
clean()
time.sleep(1)
print """
Timer Finished.
"""
Some problems in your code are, the unnecessary use of globals, direct typechecking, etc. Also if you use higher level constructions(like timedelta objects) the probability of your code being bug free is higher. This is better:
from datetime import timedelta
from time import sleep
while True:
try:
hours, minutes, seconds = input('Enter hours, minutes, seconds (with a comma in between): ')
except (ValueError, TypeError): # other errors
print("Error 1, please ...")
continue
except NameError:
print("Error 2")
continue
else:
print("All good")
break
total = timedelta(hours=hours, minutes=minutes, seconds=seconds)
for passed_seconds in range(int(total.total_seconds())):
print total - timedelta(seconds=passed_seconds)
sleep(1)

Python 2.7 While Loop time

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?
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.
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

Categories

Resources