I do not code with python but I have to write a simple game in python, the process is the program make 2 random numbers and ask the user what is the sum of these two numbers and the user have 5 seconds to answer it if it gets more than 5 seconds it should says Time Out and show the point, else if the user answered correctly under 5 second it should terminate or kill the time function, make other random numbers and ask the sum of them
the input function blocks the program and wait for input so I have made two processes and I'm not sure I did right or no, it still doesn't work in parallel also looks like the sleep function blocks the program too
I have search a lot about parallel programming and non-blocking input in python but I couldn't fix it
import random
import time
from multiprocessing import Process
point = int(0)
check = bool(False)
def runInParallel(*fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
def timeingFunc():
timer = int(3)
time.sleep(timer)
print("Time Out")
print(point)
def logic():
counter = 0
+(+counter)
x = random.getrandbits(2)
y = random.getrandbits(2)
print("%3f + %2f = " % (x, y))
result = int(input())
if result == int (x + y):
+(+point)
print("Good")
check = True
if __name__ == '__main__':
while 1>0:
runInParallel(logic(),timeingFunc())
Related
Example
x = 0
while True:
x += 1
input = input("whats the day like")
I want it so x will continue going up while waiting for the input
Instead of using a counter look at time module and calculate time before and after the user input and take the difference to get the time taken for user input.
use time.time() to capture the time at particular instance.
If you are doing this just for timing:
from time import perf_counter
start = perf_counter()
inp = input()
print(inp)
print(f"You inserted input in : {perf_counter() - start}")
If by any reason you want to increment x, do the increment part in a separate thread:
from time import sleep
import threading
x = 0
def increment():
global x
while True:
x += 1
print(f"X is now: {x}")
sleep(1)
threading.Thread(target=increment, daemon=True).start()
inp = input()
print(f"input is: {inp}")
output:
X is now: 1
X is now: 2
X is now: 3
hi
input is: hi
By specifying daemon=True, the increment thread doesn't prevent interpreter from terminating.
If you want to stop the thread whenever you receive input, use event object:
from time import sleep
import threading
event = threading.Event()
x = 0
def increment():
global x
while not event.is_set():
x += 1
print(f"X is now: {x}")
sleep(1)
threading.Thread(target=increment).start()
inp = input()
event.set()
print(f"input is: {inp}")
It's great to see a new user on StackOverflow.
I was able to find a solution using the threading module in Python. One way to think about threading in Python is by imagining two Python scripts running simultaneously, but this is not an entirely thorough explanation. To learn more, I would suggest referring to one of the pages below.
Links:
https://realpython.com/intro-to-python-threading/#what-is-a-thread
https://docs.python.org/3/library/threading.html
Example:
import threading
def thread_function(args):
for x in range(args):
print(x)
x = threading.Thread(target=thread_function, args=(5,))
x.start()
input = input("whats the day like")
Output:
0
1
2
3
whats the day like4
Where it waits for user input at the end.
I'm a complete beginner in programming and just wanted to code something I thought was interesting in python. I want to code the rest of it myself, but I got stumped on this part and cannot figure it out at all.
This is my code so far...
block, is the name I gave each session where users can input numbers
there are 3 blocks where users are given 5 seconds of time in each block
to enter (as many sequences of "5" numbers) as they can.
each time the user enters a sequence of numbers, it should add those values to an index in the block_list. (doesn't matter if they enter 3 or 8 values)
Here's the problem:
So after entering some numbers in, as soon as the timer runs out, I want the program to submit whatever the user is inputting to the list and skip to the next block iteration.
My code just doesn't do this and it also is stuck in a loop as well
Looking for help thanks!
Here is the output:
OUTPUT
and here is the code:
from threading import Thread
import time
from random import *
block = 0
def main():
global block
while block < 3:
Thread(target=userInputs).start()
Thread(target=countTime(5)).start()
block += 1
block_list = []
timeOut = True
def userInputs():
while timeOut == True:
num_inputs = int(input("Input 5 numbers and then press 'enter': "))
block_list.append(num_inputs)
print(block_list)
start_time = time.time()
num_list = [1,2,3,4]
block_list = []
def countTime(seconds):
global timeOut
global start_time
while True:
elapsed_time = time.time() - start_time
if elapsed_time >= seconds:
print()
print("Time spent:")
print(time.time()-start_time)
timeOut = False
break
timeOut = True
start_time = time.time()
print(start_time)
main()
I have made a timer while loop using
while True:
time.sleep(1)
timeClock += 1
is it possible to execute this loop while executing another infinite while loop at the same time in the same program because I have made a command to show the elapsed time whenever I want
The whole Code is
def clock():
while True:
time.sleep(1)
t += 1
print(t)
clock()
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == Y:
print(t)
else:
pass
Thanks in advance
You can do a very similar thing with multiprocessing...
from multiprocessing import Process, Value
import time
def clock(t):
while True:
time.sleep(1)
t.value += 1
t = Value('i', 0)
p = Process(target=clock, args=[t])
p.start()
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == 'Y':
print(t.value)
Multiprocessing has more overhead than multithreading, but it can often make better use of your machine's capabilities as it is truly running two or more processes in parallel. Python's multithreading really doesn't, due to the dreaded GIL. To understand that, check this out
If you want multiple loops running at the same time, you should use multi-threading. This can be done using the threading library as shown below:
import threading
import time
def clock():
global t
while True:
time.sleep(1)
t += 1
print(t)
x = threading.Thread(target=clock)
x.start()
t = 0
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == 'Y':
print(t)
else:
pass
If the only purpose is a clock however, you'd be better off following kaya's advice and using the time library itself.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I made a program on checking if an user-input number is prime or not. However, when I enter large numbers, it takes a considerable amount of time. What sort of code would help to show the user that the number is being checked upon, something similar to a loader, unless the result has been determined? The code is as follows:
from math import sqrt as s
from time import time as t
def check_prime(p):
prime = [p]
start = t()
if p > 3:
for i in range(2, int(s(p)) + 1):
if p % i == 0:
end = t()
print('Time taken is', end - start, 'seconds')
prime.remove(p)
break
else:
continue
else:
pass
try:
end
except:
end = t()
print('Time taken is', end - start, 'seconds')
if p in prime:
if p == 2 or p == 3 or (p != 1 and p > 0):
return(f'{p} is a prime number')
elif p <= 0:
return(f'{p} is not in the domain of prime or composite numbers')
else:
return('1 is neither prime nor composite')
else:
return(f'{p} is NOT a prime number')
while True:
p = input('> ')
print(check_prime(int(p)))
I think the simplest solution to get an animated loader (as I guess that's what you asked for) that can be inserted anywhere is something like this:
import sys, threading, time
loading = True
def loader(*args):
while loading:
time.sleep(0.5)
sys.stdout.write('[-]' + '\b'*3) # Write loader and return to start of line
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('[/]' + '\b'*3)
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('[|]' + '\b'*3)
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write('[\]' + '\b'*3)
sys.stdout.flush()
t = threading.Thread(target=loader)
t.start()
# Do some work here
loading = False
To avoid creating a thread, you can do this in your loop while checking if your number is prime.
You could print to the console something like a loading bar( for example, using _ characters ). Therefore, you could add a new '_' char to the console buffer whenever a percentage of the given operations that you perform is being processed.
You could do that in the loop inside the "check_prime" function, as I do not suggest assigning this task to another thread, as there are several situations that you'd have to take into consideration.
Hey guys I'm doing a program in python. It's a calculation program which gives you two random number from 2 to 10, and then asks you for example how much is 2 * 4.
And if your answer is correct it gives you a point. Now, I want that the program let's the user calculate for 20secs and when 20secs are over, it will show you how much points you have.
My code so far ->
__author__ = 'Majky'
import random
import time
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
t = 0
odg = int(input("Answer ?"))
sec = 0
while sec < 20:
if odg == a * b:
print("Correct")
t = +1
print("Incorrect")
print("Your points are", t)
You are going to want to use threading, and open a parallel thread that will calculate that time (maybe by using time.sleep()) and return once done, once it returns, the main thread will stop execution and return the results.
Using sleep() in the main program will just pause execution for that time, which is not what you want from what I understand. You want the user to be able to interact with the program while the timer is running. That is what using threads from the threading module will allow you to do.
Here is a quick example of the use of threading (adjust it if you need anything specific):
import random
import time
def main():
thread_stop = threading.Event()
thread = threading.Thread(target=user_thread, args=(2, thread_stop))
time.sleep(20)
thread_stop.set()
def user_thread(arg1, stop_event):
t = 0
while(not stop_event.is_set()):
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
odg = int(input("Answer ?"))
if odg == a * b:
print("Correct")
t += 1
else:
print("Incorrect")
print("Your points are", t)
main()
Here is also an example using signals that stops the user in the middle of an answer if the 20 seconds are up and counts the results. This example uses signals, which is in itself an interesting module to control execution flow, you should check its documentation when you get a chance. I also realized there was another error in your code which I overlooked and has been corrected now in both examples, when you want to increase "t", use "t+=1", since "t=+1" is incorrect, the last expression is just assigning "positive" one to t every time, so is not increased. Cheers!
import signal
t = 0
#Here we register a handler for timeout
def handler(signum, frame):
#print "Time is up!"
raise Exception("Time is up.")
#function to execute your logic where questions are asked
def looped_questions():
import random
global t
while 1:
#Here is the logic for the questions
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
odg = int(input("Answer ?"))
if odg == a * b:
t += 1
print("Correct")
else:
print("Incorrect")
#Register the signal handler
signal.signal(signal.SIGALRM, handler)
#Set the timeout
signal.alarm(20)
try:
looped_questions()
except Exception, exc:
print exc
#Here goes the results logic
print("Your points are", t)
Also, don't forget to add to that sanity checks so that invalid user input doesn't break your code. I will leave that to you ;)
You could use the time.sleep(20) function to wait 20 seconds.
This function suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.
you could do something like this, using time.time().
import time
...
start = time.time()
answer = raw_input('enter solution')
finish = time.time()
if finish - start > 20:
#failure condition
else:
#success condition