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)
Related
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()
I'm having trouble figuring out this code. I am currently making a script in python where a it's kind of how an arcade machine works when you have 30 seconds to continue and you can insert more coins to go again. The trouble I'm having is I cant get the coins to count up while the timer counts down. Here is my code so far:
while True:
start = GPIO.input(startBtn)
input_state = GPIO.input(counterPin)
if input_state == False:
coins += 1
print(str(coins) + "¢ inserted")
time.sleep(0.09)
if coins == 100:
coins -= 100
creditss += 1
print("You currently have: " +str(creditss) + " credits")
timer = creditss * 5
if start == False:
if creditss > 0:
print("You have: " +str(timer) + " minutes to play!")
print("Have Fun!")
x = timer
for i in range(x + 1):
time.sleep(1)
print(formatTime(x))
x -= 1
timer -= creditss * 5
creditss = 0
if timer == 0:
pause()
timer += 30
print("Continue? : Insert more money to keep playing!")
x = timer
if input_state == False:
coins += 1
print(str(coins) + "¢ inserted")
time.sleep(0.09)
else:
for i in range(x + 1):
time.sleep(1)
print(formatTime(x))
x -= 1
if coins == 100:
coins -= 100
creditss += 1
print(creditss)
if creditss > 0 & timer != 0:
print("Good")
pause()
else:
print("exit")
os.system('/home/pi/exit.sh')
Thanks for any help!
Okay...the best help I can give you is this:
At this point you need to refactor your code. When you get a program with more than two - three levels of nesting (you have four if statements nested) then you should be defining functions and splitting out different parts of your program into logical chunks. This makes debugging easier, as you can drop I/O print statements to see where your script is failing.
To help you know what to split out first - look for sections where you're repeating yourself. If you type it more than once, it deserves its own function (DRY Principle - Don't repeat yourself).
for example you have:
if coins == 100:
coins -= 100
creditss += 1
print("You currently have: " +str(creditss) + " credits")
timer = creditss * 5
and
if coins == 100:
coins -= 100
creditss += 1
print(creditss)
This functionality is extremely similar and can likely be split off into a function. The other thing you want to think about: You only want /one/ part of the program to be able to change the number of coins so that you know when you're calling it what's happening (explicit is better than implicit). That should be a function and anything that needs to operate it can call it. The easier your program is to read, the easier it will be to debug. At least until you get issues that silently fail.
The sleep function stops execution, so during countdown every time you sleep you stop checking the GPIO state for a whole second and then just check it once more until sleeping again for another second. For this strategy to work you need to be checking your input very fast as to not miss a fast event. My guess is that checking once every one second is probably not enough for what you are doing.
A sightly better solution would be to not sleep and to use time.clock() to check when the play time has ended. So when the game starts you store the current value of time.clock() and after that you continue checking it until enough time has elapsed. There could still be an input which unsets and sets your input pin faster your loop can detect it so it's not bulletproof.
I don't have experience with python on raspberry-pi but a quick google search shows me there are GPIO.add_event_detect() and GPIO.add_event_callback() functions which can be set up so a callback function is called on a GPIO pin state change, which I would guess relies on interrupts so that you wouldn't miss an event. It could be a good idea to look into that.
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
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
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