I am trying to write a program that will measure a user's typing speed however I cannot get the loop where the user inputs to terminate when the time is up. I want the loop to stop as soon as the time is finished.
from datetime import datetime, timedelta
text = 'Hello My name is matthew'
def some_function(duration):
end_time = datetime.now() + timedelta(seconds=duration)
while datetime.now() < end_time:
answer = input('Type the following: ' + text + '\n\n')
duration = int(input('How long do you want to test yourself: '))
some_function(duration)
The problem is that input() is blocking. The rest of the code isn't executed until the user submits their input by pressing enter. You should check out this thread for non-blocking console input
Related
I want to set time to notify the user by a flexible time I mean I want to input a time.
I can get my desire output with a specific time, but when I input my desired time, It does not go through the program. again ask for input time:
I need to print the time and notify and continue the program:
20:24:00
>
>>> from win10toast import ToastNotifier
>>> import time
>>> def run_app():
>>> show_help()
>>> while True:
>>> #set time to notify for shopping
>>> notification_time = time.strftime("%H:%M:%S")
>>> if notification_time == input("Please enter a specific time:\n"):
>>> print(notification_time)
>>>
>>> break
>>> else:
>>> pass
>>> #organise the notification
>>> notification1= ToastNotifier()
>>> notification1.show_toast("Alarm","It is time to shop ")
the result now is:
Please enter a specific time:
20:24:00
Please enter a specific time:
...
The logic of your input loop is faulty. It does not at all match what you say you want to do:
notification_time = time.strftime("%H:%M:%S")
# This stores the current time, mis-named "notification_time"
if notification_time == input("Please enter a specific time:\n"):
# This requires the user to enter a time in the required format.
# If that doesn't match the current time at the previous instruction,
# you ignore the input and repeat the process.
Finally, if the user does manage to enter the current time while it is still current, you take that as the notification time. The user has no way to enter a time in the future.
Instead, you need to accept the user's notification time, and then check that format for validity. The easiest way is usually to accept the input string, and then use a try/except block to convert it to a time. If that fails you loop back to try the input again.
I've tried to make your idea into a functional code:
from datetime import datetime
import time
from win10toast import ToastNotifier
toaster = ToastNotifier()
# Validate if the format of the time that the user submitted is correct
def isTimeCorrect(input):
try:
time.strptime(input, '%H:%M:%S')
return True
except ValueError:
return print('time is wrong')
# Request the user to type the alarm time
alarm = input('Type your alarm time in this format HH:MM:SS\n')
# Get the current time
now = datetime.now()
# Format the current time
current_time = now.strftime("%H:%M:%S")
# Loop and check the current time until it's the same as the alarm
while (isTimeCorrect(alarm)):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
# Check if the current time is the same as the alarm
if current_time == alarm:
# throw the notification
toaster.show_toast("Example","Notifcation Text",icon_path=None,duration=5,threaded=True)
break
import time
import os
T = int(input("Enter desired time for the timer - "))
t = time.localtime(time.time())
def Timer():
while ((t.tm_sec) != T+(t.tm_sec)):
return t
else:
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
I have been working on this timer and can't get it to work. Basically, I want it to play the song I have in my system when the time is up. I have been trying to write this program and I can't understand why my code doesn't run the way I want it to. Could someone please point out if there's a mistake in it?
What's wrong with your code specifically is this condition
(t.tm_sec) != T+(t.tm_sec)
The problem is that t's value was set when you did (t.tm_sec) != T+(t.tm_sec). Once that is set, the same value of t will be used. I think you assumed that t will be recomputed every time in the while statement. To recompute t every time you can do:
import time
import os
T = int(input("Enter desired time for the timer - "))
snap_time = time.localtime(time.time())
def Timer():
t = time.localtime(time.time())
while t.tm_sec < (T + snap_time.tm_sec):
t = time.localtime(time.time())
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
t.tm_sec is fixed, so unless T is 0 the condition will never be False, so the else block will never be executed. On top of that there is return in the loop, which mean it will run only one iteration and exit the function. Try
T = int(input("Enter desired time for the timer - ")) + time.time()
def Timer():
while time.time() < T:
pass
else:
os.system("start C:/Users/Public/Music/Sample Music")
You can also remove the else
def Timer():
while time.time() < T:
pass
os.system("start C:/Users/Public/Music/Sample Music")
I don't think your example makes proper use of while (and return). How about a much simpler version:
import time
import os
T = int(input("Enter desired time for the timer - "))
def Timer():
time.sleep(T)
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
import time
print("The timer on this project Will start")
#Ask To Begin
start = input('Would you like to begin learning now? (yes / no):')
if start == 'yes':
timeloop = True
#variable to keep the time
Sec = 0
Min = 0
#Begin process
timeloop = start
while timeloop:
Sec +=1
print(str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min +=1
print(str(Min) + " Minute ")
This is my timer program so far but I am not sure How I can get it to stop once it starts in the command prompt?. I want to be able to press X and have the code pause. Or perhaps press Y and then it resumes, and Z just closes the program all together, but I have no idea as to how.
time.sleep actually stop the execution of the current process the code is running on. If you want to keep time and still make the process responsive, you may want to use a thread to keep time and install the keyboard package to use keyboard.is_pressed()!
This article is really good:
https://realpython.com/intro-to-python-threading/#what-is-a-thread
I'm totally new to programming. Wanted to write this basic alarm clock with Python but the webbrowser just doesn't open. I think it is probably my if statement that doesn't work. Is that correct?
from datetime import datetime
import webbrowser
name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
now = datetime.today()
print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))
if now.hour == alarm_h and now.minute == alarm_m:
webbrowser.open(alarm_sound, new=2)
You can try this simple example.
from datetime import datetime
import webbrowser
import threading
name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
print alarm_sound
now = datetime.today()
def test():
webbrowser.open(alarm_sound)
s1 = '%s:%s'
FMT = '%H:%M'
tdelta = datetime.strptime(s1% (alarm_h, alarm_m), FMT) - datetime.strptime(s1%(now.hour, now.minute), FMT)
l = str(tdelta).split(':')
ecar = int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
print ecar
threading.Timer(ecar, test).start()
We use threading to open a webbrowser after n seconds. in you example you ask user for hour and minute, in this way we calculate diffrence between two times using just hours and minutes.
If you need more explanation just comment.
Your current code looks like it is checking the current time against the set alarm time. However, you currently have just one check, but you need to either loop and continuously compare the current time with the set alarm time or use another method of continuously checking.
The webbrowser line does work. Its not executing because the current time never reaches the alarm time (since you are not continuously comparing the current time with the set alarm time).
Try:
from datetime import datetime
import webbrowser
name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
now = datetime.today()
print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))
webbrowser.open(alarm_sound, new=2) #Added temporarily to test webbrowser functionality
if str(now.hour) == alarm_h and str(now.minute) == alarm_m: #Converted integer type to string type to match datatype of alarm_h and alarm_m
webbrowser.open(alarm_sound, new=2)
This should open the webbrowser so you can test its functionality.
I also converted now.hour and now.minute to type string to match the datatypes of alarm_h and alarm_m. They were both integers and which can't be directly compared to a string datatype.
Definitely look into looping or threads for continuously updating the current time and checking if it equals the current thread.
I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():