So I am wanting to create a program that allows for a limited time for user input. I want the countdown timer that continuously gets updated; while asking for user input on a different line. Currently, the countdown timer is printing to the same line as the user input line. How can I get them on separate lines? Or how do I cancel out user input after a specific time?
def showTime():
h = 0
m = 1
s = 0
total_seconds = h * 3600 + m * 60 + s
while total_seconds > 0:
timer = datetime.timedelta(seconds=total_seconds)
print(timer, end="\r")
time.sleep(5)
total_seconds -= 5
print("Out of time")
def main():
p = Process(target=showTime)
p.start()
user_input = input('\nPlease enter your answer: ')
if user_input == A:
p.terminate()
print('Correct')
else:
p.terminate()
print('Incorrect')
if __name__ == '__main__':
main()
Related
import random
import time
import pathlib
import hashlib
import operator
level = 1
score = 1
def sign_up():
username = input("Enter a username: ")
while True:
password = input("Enter a password (6 character long): ")
if len(password) < 6:
password = input("Enter a password (6 character long): ")
else:
break
hashed_password = hashlib.sha1(password.encode("utf-8")).hexdigest()
# print(hashed_password)
with open("credentials.txt", mode="w") as writable_password:
writable_password.write(username+"\n")
writable_password.write(hashed_password+"\n")
log_in()
def log_in():
print("Please, enter your usarname and password to sign in")
username = input("Username: ")+"\n"
while True:
password = input("Password (6 character long): ")
if len(password) < 6:
password = input("Password (6 character long): ")
else:
break
with open(".credentials.txt", mode="r") as credentials:
user_data = credentials.readlines()
for i in user_data:
# print(i)
if i == username and hashlib.sha1(password.encode("utf-8")).hexdigest()+"\n" == user_data[user_data.index(i)+1]:
print("You have succesfully signed in")
start_game()
break
def start_game():
start = "ll"
start = input("Please press any key to start the game")
# print(start)
if start != "ll" and level == 1:
level_one()
overall = 0
def level_one():
global score
global overall
if score <= 0:
return print("Haha, You lost")
answer = 0
first_number = random.randint(1, 100)
second_number = random.randint(1, 100)
random_operator = random.choice(["+", "-"])
if random_operator == "+":
response = input(f"{first_number} + {second_number}: ")
answer = first_number + second_number
if int(response) == answer:
score += 10
overall += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
else:
response = input(f"{first_number} - {second_number}: ")
answer = first_number - second_number
if int(response) == answer:
score += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
# print(first_number, second_number, answer)
# def main():
# if __name__ = "__main__":
# main()
# sign_up()
# log_in()
start_game()
I want to implement a timer for my math quiz. The user should have 2 minutes at the beginning and for each correct answer 10 seconds will be added. For wrong answers 6 sec will be removed. How can I do this with Python 3.8?
I would add a new methode and using the threading.Timer modul (https://docs.python.org/3/library/threading.html#timer-objects):
from threading import Timer
global time_to_play
time_to_play=2*60 # in seconds
....
def check_for_end:
if time_to_play == 0: # time runs out
print("You lose")
exit(0) # exit program
else: # still playing
t = Timer(2.0, check_for_end) # start Timer wich runs the check methode in 2 sec
t.start()
and now you just have to adjust the global variable time_to_play accordingly.
The Timer will check all 2 seconds, if time_to_play is 0
what I have is
import time
r = 0
while True:
print(r)
r += 1
time.sleep(3)
number = input()
num = int(number)
#????????????
if num == r:
print('yes')
else:
print('no')
And what I want to do is make it so after every number printed there's a 3 second window for the user to input the value of r, and if the user does nothing then have the program move on. How do I do that?
Here is a working code using signal and Python 3.6+ That should run under any Unix & Unix-like systems and will fail under Windows:
import time
import signal
def handler_exception(signum, frame):
# Raise an exception if timeout
raise TimeoutError
def input_with_timeout(timeout=5):
# Set the signal handler
signal.signal(signal.SIGALRM, handler_exception)
# Set the alarm based on timeout
signal.alarm(timeout)
try:
number = input(f"You can edit your number during {timeout}s time: ")
return int(number)
finally:
signal.alarm(0)
r = 1
while True:
number = input("Enter your number: ")
num = int(number)
try:
num = input_with_timeout()
# Catch the exception
# print a message and continue the rest of the program
except TimeoutError:
print('\n[Timeout!]')
if num == r:
print('yes')
else:
print('no')
Demo 1: Execution without timeout
Enter your number: 2
You can edit your number during 5s time: 1
yes
Enter your number:
Demo 2: Execution with timeout
Enter your number: 2
You can edit your number during 5s time:
[Timeout!]
no
Enter your number:
hello i have a code that looks like this
from multiprocessing import Process
from tkinter.messagebox import *
from time import sleep
def timerclose():
sumtimer = 0
while sumtimer <= 10 :
sleep(0.1)
sumtimer = sumtimer + 0.1
print("sumtimer",sumtimer)
return sumtimer
def conout():
confirmation = askokcancel ("confirmation","are you sure ?")
return confirmation
if __name__=='__main__':
p1 = Process(target=timerclose)
p1.start()
p2 = Process(target=conout)
p2.start()
I wanted to create an askokcancel message box with a timeout. i want the messagebox to popout to ask the user if we wants to exit or not and simultaneously starts a counter. after 10 seconds if the user does not press anything (ok or cancel) i would get the return value from the timerclose ignore the conout function and continue with the rest of the programm.
i solve it with one process and a shared value
def conout(n):
n.value = int(0)
confirmation = askokcancel ("confirmation","Σε 10 sec κλείνω Οκ ?")
if confirmation == True :
n.value = int(1)
else:
n.value = int(2)
if __name__=="__main__":
p2 = Process(target=conout, args=(num,))
p2.start()
timerls = 0
while timerls <= 10:
sleep(0.25)
timerls += 0.25
print("timerls",timerls)
if num.value == 1 :
print ("end true",num.value)
break
elif num.value == 2:
print ("end false", num.value)
break
else:
print ("end0", num.value)
I am currently learning python 3.6.5, and I am interested in learning about an auto-clicker that opens a page types a URL/goes to it then waits a few seconds clicks something else then closes web browser and repeats process x amount of times. Where do I begin?
Please try to get help from this code:
import win32api
import win32con #for the VK keycodes
import time
import msvcrt as m
import signal
import sys
def mouseClick(timer):
if not check_off_pos():
print("Click!")
x,y = win32api.GetCursorPos()
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
time.sleep(timer)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
time.sleep(timer)
global count
count = count + 1
if count >= 3 / (timer * 2):
cast_spell(timer)
count = 0
def cast_spell(timer):
print("Cast Spell!")
global spell_x
global spell_y
global tx
global ty
x = spell_x
y = spell_y
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
time.sleep(timer)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
time.sleep(timer)
win32api.SetCursorPos((tx, ty))
time.sleep(timer)
def getPos():
x,y = win32api.GetCursorPos()
return x, y
def wait():
m.getch()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
def check_off_pos():
global tx
global ty
a, b = getPos()
if abs(a - tx) > 100 or abs(b - ty) > 100:
return 1
return 0
input("Press Enter to capture of chest...")
tx, ty = getPos()
input("Press Enter to capture of spell...")
spell_x, spell_y = getPos()
count = 0
options = []
signal.signal(signal.SIGINT, signal_handler)
print("Press Ctrl+C")
sleep = 0
while True:
mouseClick(0.03)
a, b = getPos()
if check_off_pos():
print('sleeping')
time.sleep(3)
sleep = sleep + 1
if sleep == 5:
input("Press Enter to restart...")
else:
sleep = 0
Source:
http://nghenglim.github.io/autoclicker-with-python/
I want to input a series of numbers and end with "stop", the while loop is to check if x is not equal to the 'stop', it continues add up the input number and output the sum for each loop, however the while loop falls into infinity. For example, my input is:
12
35
56
23
56
455
556
344
22
22
stop
#read the input
x = input()
#add up by a loop
T = 0
x_int = int(x)
while x != 'stop':
for i in range(1, 10):
T += x_int
print(i, T)
You need to prompt for the next input in the while loop. As stands, you never prompt for additional data and so you will never see the stop. I added a prompt so that it is more clear.
#add up by a loop
T = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
x_int = int(x)
for i in range(1, 10):
T += x_int
print(i, T)
Several of us are confused about how you want to enter data. If you don't want any prompts and want to read any number of lines from the user (or perhaps piped from another program) you could read stdin directly.
#add up by a loop
import sys
T = 0
for line in sys.stdin:
x = line.strip()
if x == 'stop':
break
x_int = int(x)
T += x_int
print(i, T)
Try this program and see if it works. The problem with your code was there is no need of a for loop. I didn't understand why it was used there in your program, hope you understood.
T = 0
i = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
else:
i =i+1
x_int = int(x)
T += x_int
print(i, T)