Why isn't my alarm code printing the message at the end? - python

So I'm fairly new to Python and I am trying to write a code for a timer. My code is supposed to get the hour, minute, whether it's AM or PM, and a message that they want the program to print out when their timer is done. As of now, the program asks several questions and stores them in variables, but doesn't print out the message when it is done.
I have tried looking at each part of the code and the code is fairly simple so I don't understand why this is occurring.
# Set up variables
hour = int(input('What should the hour be? '))
minute = input('What should the minute be? ')
ampm = input('A.M. or P.M.? ')
if (ampm == 'A.M.'):
if (hour == 12):
hour = 0
else:
hour = hour
if (ampm == 'P.M.'):
if (hour == 12):
hour = hour
else:
hour = hour + 12
message = input('What should the message be? ')
import datetime
current_hour = datetime.datetime.today().strftime('%H')
current_minute = datetime.datetime.today().strftime('%M')
alarm = True
# Set up loop
while (alarm):
if (hour != datetime.datetime.today().strftime('%H')):
alarm = True
else:
if (minute == datetime.datetime.today().strftime('%M')):
print(message)
alarm = False
else:
alarm = True
It is supposed to print out the message that the user inputted. It's not doing that.

The variable of hour returns an int value and datetime.datetime.today().strftime('%H') returns string so your program get in the infinite loop.Change condition like
if (hour != int((datetime.datetime.today().strftime('%H')))):

Related

How to match current date and specific date in Python

I'm developing a reminder app in Python. My question is when I execute my code. It should wait until current date equals to specific date. But it's not working, here's my code.
CODE:
from threading import Thread
from datetime import datetime, timedelta
# Current date, 8/15/2020 - 10:00
a = datetime.now()
# Specific date (1 minute later from current date), 8/15/2020 - 10:01
b = a + timedelta(minutes = 1)
# Reminder name
d = "stack reminder"
# Reminder list
c = {}
# Target function
def createThread():
while True:
if(b.second == a.second and
b.minute == a.minute and
b.hour == a.hour and
b.day == a.day and
b.month == a.month and
b.year == a.year):
print("worked")
# If thread name in reminder list
if d in c:
print("canceling")
t.cancel()
break
# Set thread and thread name and print thread name
t = Thread(target = createThread)
t.setName(d)
print(t.getName())
# Append reminder name to reminder list and print
c[d] = b
print(c)
# Start thread
t.start()
This code isn't working. Is if statement wrong? I'm creating Thread because while program waiting for specific date, I want to do different things. Where is my fault and how to run this code?
You are never updating the a variable again.
datetime.now() doesn't constantly update so you will have to call this in your thread.
a = datetime.now() in every iteration of your while loop.
At the moment you are never getting get your if condition to match as the time in a stays in the past.
Also you should be able to simplify this.
(b.second == a.second and
b.minute == a.minute and
b.hour == a.hour and
b.day == a.day and
b.month == a.month and
b.year == a.year):
To just simply
if b == a:
As both should be datetimes.
But its probably better to do use > in your condition as by using == you would have to match to the millisecond. Even matching to the second could cause issues and the condition might be missed.
i.e
If "a" (i.e the current time) >= "b" the time you want to check for.
Then fire the condition.
or put another way... If the current time is greater than or equal to the calendar entry time - then its time to alert the user.
if a >= b:
Complete Example:
from threading import Thread
from datetime import datetime, timedelta
# Current date, 8/15/2020 - 10:00
# Specific date (1 minute later from current date), 8/15/2020 - 10:01
b = datetime.now() + timedelta(minutes = 1)
# Reminder name
d = "stack reminder"
# Reminder list
c = {}
# Target function
def createThread():
while True:
a = datetime.now()
if a > b :
print("worked")
# If thread name in reminder list
if d in c:
print("canceling")
t.cancel()
break
# Set thread and thread name and print thread name
t = Thread(target = createThread)
t.setName(d)
print(t.getName())
# Append reminder name to reminder list and print
c[d] = b
print(c)
# Start thread
t.start()

When user inputs same input twice (expected), how do I combine the input to output?

My test code works for the first record with one day entered but the body of the code does not work. The code continues to run asking for the day and hours worked. I enter "done" and it doesn't accept that either.
I initially thought creating a list for the days entered but wasn't sure when to access the list to print the footer before going to the next input. There are no errors just won't execute as expected. This is an assignment and many of the declarations were already populated.
Expected Results with user input:
Day worked: Tuesday
Hours Worked: 3
Day worked: Tuesday
Hours Worked: 4
Day Total 7
Here's my code.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done" # Named constant for sentinel value
hoursWorked = 0 # Current record hours
hoursTotal = 0 # Hours total for a day
prevDay = "" # Previous day of week
notDone = True # loop control
days=[]
# Print two blank lines.
print("\n\n")
# Print heading.
print("\t" + HEAD1)
# Print two blank lines.
print("\n\n")
# Read first record
dayOfWeek = input("Enter day of week or done to quit: ")
if dayOfWeek == SENTINEL:
notDone = False
else:
hoursWorked =int(input("Enter hours worked: "))
prevDay = dayOfWeek
hoursTotal = hoursWorked
days.append(dayOfWeek)
print("\t" + DAY_FOOTER + str(hoursTotal))
print(days)
while notDone == True:
dayOfWeek = input("Enter day of week or done to quit: ")
prevDay = dayOfWeek
hoursWorked =int(input("Enter hours worked: "))
hoursTotal = 0
hoursTotal = hoursTotal + hoursWorked
days.append(dayOfWeek)
print(days)
def dayChange(DAY_FOOTER,hoursWorked):
if dayOfWeek == dayOfWeek:
DAY_FOOTER = dayOfWeek
hoursTotal = (hoursWorked + hoursWorked)
print("\t" + DAY_FOOTER + str(hoursTotal))
days.append(dayOfWeek)
else:
print("\t" + DAY_FOOTER + str(hoursTotal))
def endOfProgram(done):
if dayOfWeek == "done":
notDone == False
return```
There are several issues with the code:
First of all, you are not really sensitive to the "done" command within the while loop. You do test the notDone variable, but you never write to this variable while inside the loop. The test should be embedded in the loop itself, and is superfluous outside it. Second of all, with each iteration of the while loop you initialize the hoursTotal variable to 0, so that you do not memorize the values from the previous days. Perhaps you should use an additional list for keeping track of hours, or use a day_of_the_week:hours dictionary.

How to call another script in one script, and run them at the same time?

I am very new to Python, but the project I am working on confused me.
In the project, I give multiple choices for uses to choose, one of the choices has a reminder function. So in the reminder function, the user can set reminder, and the function will match the reminder to current time every 15 seconds until they match and print a statement.
This is the code for reminder.
import time
def setReminder(number):
reminderList = []
for i in range(number):
reminderL = []
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
print()
if ((int(mon)<1 or int(mon)>12)
or (int(day)<1 or int(day)>31)
or (int(hour)<0 or int(hour)>23)
or (int(minute)<0 or int(minute)>59)):
print('invalid date and time, please set again!')
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
reminderL.extend((mon, day, hour, minute))
reminder = ''
for element in reminderL:
if int(element)<10:
element = '0' + element
reminder = reminder + element + ' '
reminderList.append(reminder)
return reminderList
def main():
num = int(input('enter the numbers of reminder you want to set(1-9):'))
if num not in range(1,10):
print('invalid input, try again!')
num = int(input('enter the numbers of reminder you want to set(0-9):'))
List = setReminder(num)
print(List)
for i in range(num):
tim = time.strftime('%m %d %H %M ')
while tim not in List:
time.sleep(15)
tim = time.strftime('%m %d %H %M ')
print('Hello, it is time to take medicine!')
main()
However, if the user set the reminder time to very late, for example next day, then this function will run until next day. Hence I want my body script to run while this reminder function is running.
This is generally how my body script is like(it is in a different script with the reminder one):
menu()
option = int(input('Your choice?'))
while (option != 4):
if option not in (1, 2, 3, 4):
print('Invalid input! Please select again!')
option = int(input('Your choice?'))
else:
if option == 1:
print()
elif option == 2:
feedback(gender, dat)
elif option == 3:
print()
print()
print('Anything else?')
menu()
option = int(input('Your choice?'))
So option 3 is the reminder, but while reminder function is try to match the time, I want the user to be able to use the other choices. The only way I think can work is to call the function and run it on another shell page. Could you give me any advice on how to do so?
The tool you need is threading. Suppose you have two separate script files: reminder.py and program.py. Then you have to delete or comment out line main() in reminder and import reminder and threading into program. Next is to modify program:
elif option == 3:
rem_thread = threading.Thread(
target=reminder.main)
rem_thread.start()
This is very basic example of how to use threads in Python. However, this addition to the code cannot solve your problem because of two reasons: (1) interference between input() calls in different threads; (2) blocking by input(). To solve the first problem you should pause main thread while user enters time parts. To solve the second problem you should start one more thread.
Here is the code that kinda works (Win10 / command prompt). There is a whole bunch of design issues to be addressed to make the code more or less usable. I tested it with 1 remainder because every remainder needs separate thread. Interference between input() and print() still present because several threads share the same console. This issue can be solved with processes instead of threads or with GUI. Of course, GUI is preferable.
import queue
import threading
import time
def setReminder(number):
reminderList = []
for i in range(number):
reminderL = []
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
print()
if ((int(mon)<1 or int(mon)>12)
or (int(day)<1 or int(day)>31)
or (int(hour)<0 or int(hour)>23)
or (int(minute)<0 or int(minute)>59)):
print('invalid date and time, please set again!')
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
reminderL.extend((mon, day, hour, minute))
reminder = ''
for element in reminderL:
if int(element)<10:
element = '0' + element
reminder = reminder + element + ' '
reminderList.append(reminder)
return reminderList
def reminder_main(wait_queue):
num = int(input('enter the numbers of reminder you want to set(1-9):'))
if num not in range(1,10):
print('invalid input, try again!')
num = int(input('enter the numbers of reminder you want to set(0-9):'))
List = setReminder(num)
print(List)
wait_queue.put('go-go-go') # unpause main thread
for i in range(num):
tim = time.strftime('%m %d %H %M ')
while tim not in List:
time.sleep(1)
tim = time.strftime('%m %d %H %M ')
print('Hello, it is time to take medicine!')
def main():
while True:
try:
option = int(input('Your choice? '))
except ValueError:
print('Cannot convert your choice into integer.')
else:
if option not in (1, 2, 3, 4):
print('Allowed options are 1, 2, 3, 4.')
else:
if option == 1:
pass
if option == 2:
pass
if option == 3:
wait_queue = queue.Queue()
# remainder thread
threading.Thread(
target=reminder_main,
kwargs={'wait_queue': wait_queue},
daemon=True).start()
wait_queue.get() # this is pause - waitng for any data
elif option == 4:
print('Exiting...')
break
if __name__ == '__main__':
# main thread
threading.Thread(
target=main).start()

employ log in hours script in python

so im Writing python script test i got from scholl but for some reason it dosen't even starts ... no error no nothing ..
its supposed to be and employes log system .. used threading for the infinite loop that's supposed to count the min and creat checking clock for the "employs" and run in background and another function that suppused to read the employ name check if his allready signed in or not and if not to add him to a file with the clock time and name or for the other way around , to log him off but for some reason the code dosent even run , no error , nothing just blank run screen, ill be glad to get some help ..
#!/bin/usr/python
from datetime import datetime
import threading
import time
users=open("logfile.txt","w")
def background():
seconde = 0
minute = 0
hour = 0
while True:
time.sleep(1)
seconde = seconde + 1
if seconde == 60:
minute = minute + 1
seconde = 0
elif minute == 60:
hour = hour + 1
minute = 0
alltime = str(hour) + ":" + str(minute) + ":" + str(seconde)
def foreground():
alin = []
name = input("Hello Deal employ , please insert your name:\n")
if name not in alin:
login=input("your not logged in , do you wish to log?\n")
if login == "yes" or "Y" or "y" or "Yes":
users.write("{} Entry Hour :".format(name) + alltime)
alin.append(name)
elif login == "no" or "N" or "n" or "No":
print("ok") and exit()
elif name in alin:
logout=input("Your allready signed in , do you wish to check out?\n")
if logout == "Yes" or "Y" or "Y" or "yes":
users.write("{} Leaving Hour :".format(name) + alltime)
elif logout == "no" or "N" or "n" or "No":
print("ok") and exit()
b = threading.Thread(name='background', target=background())
a = threading.Thread(name='foreground', target=foreground())
b.start()
a.start()
b = threading.Thread(name='background', target=background())
target should be a callable object. As is, you are running background before starting the thread. As background never stops, your program runs forever. Try:
b = threading.Thread(name='background', target=background)
I'm not sure exactly what you're trying to do, but I'm pretty sure it's not going to work.

Stopping Stopwatches

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():

Categories