I created a small app where the user can add number of instances and then add arbitrary numbers, making it all end up in a pandas df. However, attempting to challenge the user doing aforementioned process, the user ends up being able to complete the process of adding values. This should stop abruptly, if time deadline is not met.
Try run the code yourself:
import time
import pandas as pd
# define the countdown func.
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
a = int(input("Enter number of instances: "))
test3 = []
i = 0
while i < a:
pl = int(input("Enter arbitrary integer: "))
test3.append(pl)
i += 1
print(list(test3))
DF1 = pd.DataFrame(test3)
return DF1
time.sleep(1)
t -= 1
print('Game over')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
print(countdown(int(t)))
I'd suspect that I am missing an if-statement, but that is potentially what I need help doing or...?
Any help is appreciated...thx
EDIT:
import pandas as pd
from threading import Timer
timeout = 8
t = Timer(timeout, print, ['Game over'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
answer = input(prompt)
a=int(input("Enter number of instances: "))
test3=[]
i=0
while i < a:
pl=int(input("Enter arbitrary integer "))
test3.append(pl)
i+=1
print(list(test3))
DF1 = pd.DataFrame(test3)
print(DF1)
t.cancel()
Related
The program I made is like monkey typer and I want to implement a timer into my code but I don't know-how. If I make another while loop it runs separately all I want to do is have a timer running at the same time as you are inputting the words. Where do I implement the timer() the while loop? New while loop?
# imports
from words import words
import random
import time
# variables
score = 0
max_score = 10
def timer(length):
while True:
print(length)
length = length - 1
time.sleep(1)
if timer == 0:
print('Game completed \nFinal score, ', score)
break
while True:
random_word = random.choice(words)
print('\n', random_word)
user = input(':')
# if correct
if user == random_word:
score = score + 1
print('Correct!\n', 'Score,', score)
# if incorrect
if user != random_word:
print('Incorrect!\n', 'Score,', score)
score = score - 1
if score < 0:
score = 0
# made by Jack Winton
You could try using multithreading or multiprocessing to create a timer, have one thread or process working on the code and another thread running the timer. Another option is to use time = time.time() then once the loop is finished add an end = time.time() and then do overall_time = start - end but I think you are trying to do a countdown, not a timer.
I am trying to code a chess timer in which there are two timers counting down alternatingly. Only one timer runs at a time, and when a certain input is given by the user, which I am using keyboard.is_pressed("some_key") for, one timer pauses and the other begins counting down and vice versa. My problem is that to countdown by intervals of 1 second, I am using time.sleep(1) and the program will not receive user input during this time, so unless the user gives input on exactly the 1 second mark, nothing happens. How can I make the countdown process and the checking for user input process run at the same time?
Here is the code:
import time
import keyboard
def timers(t1, t2):
pause = True
while t1 or t2:
if pause:
while pause:
mins1 = t1 // 60
secs1 = t1 % 60
timer1 = '{:02d}:{:02d}'.format(mins1, secs1)
print("Timer1: ", timer1)
time.sleep(1)
t1 -= 1
if keyboard.is_pressed("w"):
pause = False
break
else:
continue
else:
while not pause:
mins2 = t2 // 60
secs2 = t2 % 60
timer2 = '{:02d}:{:02d}'.format(mins2, secs2)
print("Timer2: ", timer2)
time.sleep(1)
t2 -= 1
if keyboard.is_pressed("w"):
pause = True
break
print("Beep")
tWhite = int(input("Enter the time in seconds for White: "))
tBlack = int(input("Enter the time in seconds for Black: "))
timers(tWhite, tBlack)
while 1:
wat=water()
if wat==10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first=input("Drank?Y/N")
if first.lower()=="y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
Is there any way to wait for a couple of minutes and if no input is provided, then take the value "n" as input for the first variable?
Guess by default it will wait indefinitely. I tried using a timer function, but it cannot record any input.
What I am trying to do is to track my activities, so if I drink water I say y--> this records my activity and writes it to a file.
All help will be greatly appreciated
Here is how you can use a combination of pyautogui.typewrite, threading.Thread and time.sleep:
from pyautogui import typewrite
from threading import Thread
from time import sleep
a = ''
def t():
sleep(5)
if not a: # If by 5 seconds a still equals to '', as in, the user haven't overwritten the original yet
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
a = input()
b = input() # Test it on b, nothing will happen
Here is the code implemented into your code:
from pyautogui import typewrite
from threading import Thread
from time import sleep
while 1:
wat = water()
if wat == 10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first = 'waiting...'
def t():
sleep(5)
if first == 'waiting...':
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
first = input("Drank?Y/N")
if first.lower() == "y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
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()
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
I was trying to make a simple timer and countdown in python, but for the first question, where you pick either timer or countdown, no matter what you type, it gives you the timer instead of countdown. How do i change this?
import time
def resetVar():
x = input("Timer or countdown?:")
minsum = int(input("How long do you want the timer to go?: "))
reminder = int(input("How often do we notify you in minutes?: "))
mins = 0
countminsum = 0
mins = 0
x = input("Timer or countdown?:")
if(x == "Timer" or "timer"):
minsum = int(input("How long do you want the timer to go?: "))
reminder = int(input("How often do we notify you in minutes?: "))
print("Countdown has started.")
while mins != minsum:
time.sleep(reminder * 60)
mins += reminder
print(str(reminder) + " Minute(s) have passed")
if mins == minsum:
print("timer has ended")
resetVar()
print(x)
if(x == "Countdown" or "countdown"):
countminsum = int(input("How long shout the countdown go for?: "))
remider = int(input("How often should we notify you how much time is left? (in minutes): "))
print ("countdown has started")
while countminsum != mins:
time.sleep(remider * 60)
countminsum -= remider
printe(str(remider) + " Minute(s) have passed.")
if countminsum == 0:
print ("Countdown has ended.")
resetVar()
print (x)
You can't check if x is timer or Timer like that, as it evaluates to x == 'Timer', ("Timer" or "timer" == 'Timer'), instead you can say x in ['timer', 'Timer'].
The same goes for countdown.