简体   繁体   English

在python中同时使用两个不同的函数

[英]Using two different functions at the same time in python

import time
import random


def timer():
  correct = 1
  x = 0
  while correct != 2:
    time.sleep(0.1)
    x = x + 0.1


def round1():
  numb = random.randint(1, 100)
  print(numb)
  timer()
  ans = input(">")
  if ans == numb:
    correct = 2
    x = round(x)
    print("you did that in", x ,"seconds!")

round1()

I was trying to get both functions to run together (have the game playing and the timer going in the background) but as soon as the timer started it would let me continue the game.我试图让这两个功能一起运行(玩游戏和在后台运行计时器)但是一旦计时器启动它就会让我继续游戏。

In the given program, I have created two different functions that will work at the same time.在给定的程序中,我创建了两个可以同时工作的不同函数。 I have used threading to create thread of functions and sleep to limit the printing speed.我已经使用线程来创建函数线程并使用睡眠来限制打印速度。 In similar manner you can use game and timer function together.以类似的方式,您可以一起使用游戏和计时器功能。

from threading import Thread
from time import sleep

#sleep is used in functions to delay the print
#the below functions has infinite loop that will run together

#defining functions
def func1():
    for x in range(20):
        sleep(1)
        print("This is function 1.")

def func2():
    for x in range(10):
        sleep(2)
        print("This is function 2.")

#creating thread
thread1=Thread(target=func1)
thread2=Thread(target=func2)

#running thread
thread1.start()
thread2.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM