how to get the results of two different functions - python-3.x

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)

Related

How can create a count down timer for user input?

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

How to implement a timer for a math quiz in python?

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

Python Multiprocessing module did not work properly

I'm writing right now on a code which counts all Primenumbers up to the highest integer. The problem is that it would take way too long (about 35 days). So the solution was in our opinion the multiprocessing module, to count all Primenumbers in 4 seperated threads (process 1: starts with 1 steps +8, process 2: starts with 3 steps +8, process 3: starts with 5 steps +8, process 4: starts with 7 steps +8). That would test every odd number if it is a Primenumber.
But the following code don't work and we cant find the Problem.
Maybe one of you can help me?
from multiprocessing import Process
import time
import math
timeStart = 0
timeEnd = 0
def istTeilbar (x, y):
if x%y == 0:
return True
return False
def istPrimzahl (x):
for i in range(2, int(math.sqrt(x))+1):
if istTeilbar(x, i):
return False
return True
def schreibePrimzahlBis1 (x):
counter1 = 0
print ("x")
for i in range(1, x, 8):
if istPrimzahl(i):
counter1 = counter1 +1
print (f'Das waren {counter1} Primzahlen\n')
def schreibePrimzahlBis2 (x):
counter2 = 0
for i in range(3, x, 8):
if istPrimzahl(i):
counter2 = counter2 +1
print (f'Das waren {counter2} Primzahlen\n')
def schreibePrimzahlBis3 (x):
counter3 = 0
for i in range(5, x, 8):
if istPrimzahl(i):
counter3 = counter3 +1
print (f'Das waren {counter3} Primzahlen\n')
def schreibePrimzahlBis4 (x):
counter4 = 0
print ('counter4')
for i in range(7, x, 8):
if istPrimzahl(i):
counter4 = counter4 +1
print (f'Das waren {counter4} Primzahlen\n')
grenze = input("Die letzte zu testende Zahl:\n")
timeStart = time.time()
p1 = Process(target=schreibePrimzahlBis1, args=[int(grenze)])
p2 = Process(target=schreibePrimzahlBis2, args=[int(grenze)])
p3 = Process(target=schreibePrimzahlBis3, args=[int(grenze)])
p4 = Process(target=schreibePrimzahlBis4, args=[int(grenze)])
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
timeEnd = time.time()
print (f'Das hat ca. {timeEnd-timeStart} sekunden gedauert.')
The original code which would take way to long if you are intersted in:
import time
import math
timeStart = 0
timeEnd = 0
def istTeilbar (x, y):
if x%y == 0:
return True
return False
def istPrimzahl (x):
for i in range(2, int(math.sqrt(x))+1):
if istTeilbar(x, i):
return False
return True
def schreibePrimzahlBis (x):
counter = 0
for i in range(2, x):
if istPrimzahl(i):
if counter == 10000:
print (10000)
elif counter == 100000:
print (100000)
elif counter == 1000000:
print (1000000)
elif counter == 10000000:
print (10000000)
elif counter == 100000000:
print (100000000)
counter = counter +1
print ('Das waren')
print (counter)
print ('Primzahlen.\n')
grenze = input("Die letzte zu testende Zahl:\n")
timeStart = time.time()
schreibePrimzahlBis(int(grenze))
timeEnd = time.time()
print ('Das hat ca.')
print (timeEnd-timeStart)
print ('sekunden gedauert')
´´´
One way to parallelize tasks is to use concurrent.futures. I personally like this solution. Maybe you want to try this :
import concurrent.futures
function_A(arg1, arg2):
...
return val_A
function_B(arg1, arg2, arg3):
...
return val_B
if __name__ == '__main__':
arg1, arg2, arg3 = ...
with concurrent.futures.ThreadPoolExecutor() as executor:
future_A = executor.submit(function_A, arg1, arg2)
future_B = executor.submit(function_B, arg1, arg2, arg3)
print(future_A.result())
print(future_B.result())

If loop is repeating itself when its not needed

I recently ran into a problem where the code would start repeating itself around line 69. I don't know why this is and any help would be amazing.
Here is the code.
import time
import threading
import random
totalviews = 0
videoViews = 0
totallikes = 0
videolikes = 0
totaldislikes = 0
videodislikes = 0
subscribers = 0
videolength = 0
midroles = 0
uploadTimer1 = 0
waitTimer1 = 0
x = 0
comadymins = 0
comadysecs = 0
def timer1():
global uploadTimer1
global waitTimer1
global x
time.sleep(.75)
if x == 1:
print(uploadTimer1, 'mins remaining')
uploadTimer1 -= 1
time.sleep(60)
if uploadTimer1 == 0:
x = 0
Timer1 = threading.Thread(target=timer1)
print('')
print("you decided to start a youtube channel")
while True:
time.sleep(1.25)
print('')
print('what type of video will you make')
print('1. comedy')
print('2. gaming')
print('3. science')
print('4. check timer')
UserInput = input('')
if UserInput == '1':
if waitTimer1 == 0:
comadymins = random.randint(10, 30)
comadysecs = random.randint(0, 60)
time.sleep(0.1)
print('video length will be', comadymins, ":", comadysecs)
time.sleep(1)
if comadymins <= 29 and comadysecs <= 59:
print('would you like to upload now?')
time.sleep(.5)
UserInput = input('')
if UserInput == 'y':
print('video is uploading')
print('it will take 4 mins')
uploadTimer1 += 4
x += 1
Timer1.start()
waitTimer1 += 1
else:
print('okay')
if comadymins <= 19 and comadysecs <= 59:
print('would you like to upload now?')
time.sleep(.5)
UserInput = input('')
if UserInput == 'y':
print('video is uploading')
print('it will take 4 mins')
waitTimer1 += 1
uploadTimer1 += 4
x += 1
Timer1.start()
else:
print('okay')
else:
print('you already have a video running')
time.sleep(1)
if UserInput == '4':
print('okay')
print(uploadTimer1, "mins remaining")
any help would be amazing. I am also very new to coding so sorry if the code is messy or not to the average standards. I have only been coding for about a month and do it about 3 hrs a week if you have any recommendations that would be amazing.
your problem is, you have the same print data "would you like to upload now?" and two conditional statements that both act the same way.
you have a
if comadymins <= 29 and comadysecs <= 59:
and a
if comadymins <= 19 and comadysecs <= 59:
since you have a random number here:
comadymins = random.randint(10, 30)
something like "11" that is less than "19" and "29" at the same time so both of your conditions will fire and you will see the repeated sentence "would you like to upload now?".
you should work on the logic of your problem.
you may use elif for you second conditional statement to avoid firing in case of first statement was true, or choose a range without overlap.
try this for your first if statement:
if 19<comadymins <= 29 and comadysecs <= 59:
You have an infinite loop when you state while True:
This will run through all lines underneath it forever.
You could exit this loop by adding a break inside the loop if a certain condition is met.

Auto clicker in Python 3.6.5

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/

Resources