2 actions at the same time in python - python

I don't know how to make a function work while the program is waiting for an input.
I have tried with threading module but it didn't work. Also I've tried with the code below but it runs the function after someone have answered and not while they're thinking the answer.
import random
def whileAnswering():
print("You can do it")
a = random.randint(0, 9)
ans = 2*a
q = ""
q = int(input("Calculate 2 * %d" %(a)))
while q != int():
whileAnswering()

You can use threading or multiprocessing to implement this. Here is a code example for you:
import random
import time
from threading import Thread
class WaitForUserInput(Thread):
def run(self):
# your original code
a = random.randint(0, 9)
ans = 2 * a
q = ""
q = int(input("Calculate 2 * %d\n" % a))
# added these lines of code from my side :)
if q == ans:
print('You did it!')
def print_message():
print("You can do it")
time.sleep(3)
if __name__ == '__main__':
waiting_for_input = WaitForUserInput()
waiting_for_input.start()
while waiting_for_input.is_alive():
print_message()
You may want to look into chapter 13 from this book by Dusty Phillips

Related

I am testing out threading.Time in this little game I made, but it keeps overlapping

import time
from threading import Timer
from random import randint
print("Every wrong answer is a 3s delay; you have 30s")
end = False
def lose():
print(end)
print("Time up!")
time.sleep(1)
print("Score is",pts,", with",wrong,"wrong answers.")
time.sleep(1)
input("enter to quit")
quit()
timer = Timer(10,lose)
timer.start()
pts = 0
wrong = 0
while end == False:
a = randint(5,50)
b = randint(5,50)
print(a,"+",b)
ans = input()
if ans.isnumeric():
ans = int(ans)
if ans == a+b:
print("correct")
pts = pts+1
else:
print("wrong,",a+b)
wrong = wrong+1
print("delay")
time.sleep(3)
print("delay end")
print("")
When the timer finishes, the loop overlaps the 'lose' function, and it messes up on the line like this:
Time up!
45 + 10
55
Score iscorrect
3
, with29 0+ wrong answers.37
enter to quitwrong,p
66
delay
How do I fix this issue?
Sorry if this question has already been answered, but I want to know.
Ideally, you should probably avoid using threads altogether, as mentioned in the comments.
However, if you are going to use threads, consider using a mutex to ensure that multiple threads are not trying to write to stdout at the same time.
For example:
# setup at the beginning:
from threading import Thread, Lock
mutex = Lock()
# surrounding each print statement:
mutex.acquire()
try:
print('text')
finally:
mutex.release()

Command prompt get unselected after using Pyglet to play audio in Python 3 in Windows 10

Need to take user input immediately after the code is done playing all the sounds. But can't because command prompt will loose focus when the sounds files are loaded into memory, and hence can't take input from keyboard.
Tried using pyglet.app.run() and pyglet.app.exit()
These two functions don't seem to work and don't really understand how they are supposed to work either.
import pyglet
import time
import random
import queue
pyglet.lib.load_library('avbin')
pyglet.have_avbin=True
music1 = pyglet.media.StaticSource(pyglet.media.load('1.ogg'))
music2 = pyglet.media.StaticSource(pyglet.media.load('2.ogg'))
def play1():
music1.play()
def play2():
music2.play()
def play3():
music1.play()
time.sleep(0.15)
music.play()
def play4():
music2.play()
time.sleep(0.15)
music2.play()
key = 2
Q = queue.Queue()
def inp():
i = key
while i > 0:
i = i - 1
time.sleep(1)
x = random.randint(1, 4)
print(x)
if x == 1:
Q.put(1)
play1()
if x == 2:
Q.put(2)
play2()
if x == 3:
Q.put(3)
play3()
if x == 4:
Q.put(4)
play4()
def user():
h = input("Enter")
print(h)
inp()
user()

Progress dots with a Thread in Python

I am trying to create a thread in Python that will poll some server as long as it won't get proper answer (HTTP GET). In order to provide convenient text UI I want to print progress dots. Another dot with every connection attempt until it finish (or just another dot with every another second of waiting).
I have found something like this: http://code.activestate.com/recipes/535141-console-progress-dots-using-threads-and-a-context-/
In this example we have context manager:
with Ticker("A test"):
time.sleep(10)
I am not sure if I understand that properly. I would like to do something like:
with Ticker("A test: "):
result = -1
while result != 0:
result = poll_server()
print "Finished."
But this does not work. Any ideas?
Cheers
Python buffers your output, so many dots will appear at once. One way around that is to import sys and use that: whenever you want to print a dot, say:
sys.stdout.write(".")
sys.stdout.flush()
The flush makes the dot appear immediately.
#! /usr/bin/python3
import sys
import time
def progress(message):
i = 0
while True:
dots = ""
i = (i % 3) + 1
dots += "." * i + " " * (3 - i)
sys.stdout.write("\r{}".format(message + dots))
sys.stdout.flush()
i += 1
time.sleep(0.3)
if __name__ == "__main__":
progress("Waiting")
More useful example:
#! /usr/bin/python3
import sys
import time
def progress_gen(message):
i = 0
while True:
for x in range(0, 4):
dots = "." * x
sys.stdout.write("{}\r".format(message + dots))
i += 1
time.sleep(0.5)
sys.stdout.write("\033[K")
yield
if __name__ == "__main__":
p = progress_gen("Waiting")
for x in range(1, 100):
next(p)
if x == 3:
break
print("Finished")
You can test it online: https://repl.it/#binbrayer/DotsProgress

Addition Python Function

So I have to create a program that asks the user 5 addition questions and they can type the right answer. I am very new at python and functions in general so helpful answers only please. I know how to get random numbers and make it so the question for ex: "What is 4 + 5?" I just do not know how to ask 5 different addition questions within the function. This is what I have.
import random
def add():
num1=random.randint(1,10)
num2=random.randint(1,10)
return num1,num2
def main():
x,y= add()
plus=int(input("What is {} + {} ?".format(x,y)))
main()
I don't get an error when I run your code. Here is an answer for you:
Right now your main() is asking for an input back from the user and each time main() is called it will ask for a different number, so if you like you can do something like this:
for _ in range(5):
main()
But from the sound of it, you want to have the function main() ask all of the questions, namely - something like this:
def main():
for _ in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
Simplest is to use a counting loop:
def main():
for i in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
The following program demonstrates how to have a program ask five addition questions:
import random
import sys
def main():
for count in range(5):
ask_addition_question()
def ask_addition_question():
numbers = random.randrange(10), random.randrange(10)
answer = get_number('What is {} + {}? '.format(*numbers))
total = sum(numbers)
if answer == total:
print('That is correct!')
else:
print('Actually, the correct answer is {}.'.format(total))
def get_number(query):
while True:
try:
return int(input(query))
except KeyboardInterrupt:
print('Please try again.')
except EOFError:
sys.exit()
except ValueError:
print('You must enter a number.')
if __name__ == '__main__':
main()
Just use a for loop to ask the user 5 times
def main():
for i in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
To check if the answer is correct just you can do:
if x + y == plus: print "good"
else: print "bad"

(python) append used to list, then only return value if it hasn't been used

The title pretty much says it all. Following is the barebones of a small Japanese learning game that I wrote. I need to only print the kana if it has not already been printed in the current loop. Can anyone see what it is that I'm doing wrong? Thank you :)
#!/usr/bin/python
from os import system as cmd
from random import choice as random
from time import sleep
from sys import platform
m = ["ma", "mi", "mu", "me", "mo"]
y = ["ya", "yu", "yo"]
n = ["n"]
def get_dict(group):
if group == 1:
return m
elif group == 13:
return y
elif group == 14:
return n
elif group == 15:
return m + y + n
def clear():
if "win" in platform: cmd("cls")
if "lin" in platform: cmd("clear")
def get_kana():
global kana
return random(kana)
## Initiate ##
kana = get_dict(15)
speed = speed()
clear()
print disp
print "Please get ready!..."
sleep(5)
def chk_used():
global used_kana
numlpo = 0
while numlpo < 50:
numlpo = numlpo + 1
kana = get_kana()
if kana not in used_kana:
used_kana = used_kana.append(kana)
return kana
break
def main():
used_kana = []
while True:
clear()
print disp
print "Please write the following kana: \n"
print " " + chk_used()
sleep(3)
main()
A couple things:
In chk_used, you have the line:
used_kana = used_kana.append(kana)
There's only one problem. list.append() returns None. Every time you do this, you're appending kana to used_kana, but then you're setting the value of used_kana to None.
used_kana.append(kana)
will suffice
You define used_kana within a function
def main():
used_kana = []
But you try to refer to it globally. Python looks for a global variable and won't find one.
def chk_used():
global used_kana
The solution:
pass used kana as an argument to chk_used()
def chk_used(usedCharacters):
...
def main():
used_kana = []
...
print " " + chk_used(used_kana)
Finally:
if kana not in used_kana:
used_kana.append(kana)
return kana
break #there's no reason for this break. the return on the line before exits the function, your code will never ever execute this line.

Categories