在程序等待输入时,我不知道如何使函数正常工作。
我尝试了线程模块,但是没有用。我也尝试过下面的代码,但是它会在有人回答之后而不是在他们正在思考答案时运行该功能。
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()
答案 0 :(得分:0)
您可以使用线程或多处理来实现此目的。这是为您提供的代码示例:
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()
您可能要研究this book by Dusty Phillips的第13章