简体   繁体   English

你如何让两个函数在python中并行工作?

[英]How do you make two functions work side by side in python?

I am very new to python and am taking a course at my school, I was given the homework of making a clock that counts down from 1 or 2 hours and also shows the minutes seconds and hours the whole time. 我是蟒蛇新手并且正在我的学校上课,我接受了制作一个从1或2小时倒计时的作业的作业,并且还显示了整个时间的分钟和小时。 I started to do the code and defined 2 functions, seconds, and minutes. 我开始做代码并定义了2个函数,秒和分钟。 Seconds counts down from 60 seconds and minutes does the same thing except from 1 minute, I tried them seperatly and they worked, then I tried them together and I couldn't get them to work side by side. 秒数从60秒开始倒数,分钟完成同样的事情,除了从1分钟开始,我分别尝试了它们并且他们工作了,然后我一起尝试了它们,我无法让它们并排工作。 How can I make them do this, also, should I just be using a variable that counts down? 如果我只是使用倒计时的变量,我怎样才能让他们这样做呢? Any help is appreciated. 任何帮助表示赞赏。

from time import *
def seconds():
    while 1==1:
        time_s = 60
        while time_s != 0:
            print (time_s)
            sleep(1)
            time_s=time_s-1

            os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )

def minutes():
    while 1==1:
        time_m = 60
        while time_m!= 0:
            print (time_m)
            sleep(60)
            time_m = time_m-1`

Also, indents might be messed up. 此外,缩进可能会搞砸。

As there are sixty seconds in a minute. 因为一分钟有六十秒。 You don't need to calculate them separately. 您无需单独计算它们。 Just calculate the total amount of seconds and divide by 60 to show the minutes, and modulo 60 to show the seconds. 只计算总秒数并除以60以显示分钟数,然后以模60来显示秒数。

I think your program needs lot of alteration regarding threading 我认为您的程序需要对线程进行大量更改

this link should help u with that :-) 这个链接可以帮助你:-)

http://www.doughellmann.com/PyMOTW/threading/ http://www.doughellmann.com/PyMOTW/threading/

Your Desired Complete Program 您想要的完整计划

    import threading
    import logging
    import time

    time_m=60
    time_s=60
    time_h=24

    print ('Karthick\'s death Clock Begins')

    def seconds():
       while 1==1:
          global time_s,time_m,time_h
          time_s = 60
          while time_s != 0:
              print (time_h,':',time_m,':',time_s)
              time.sleep(1)
              time_s=time_s-1

              os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )

    def minutes():
        while 1==1:
            global time_m
            time_m = 60
            while time_m!= 0:
                time.sleep(60)
                time_m = time_m-1

    def hours():
        while 1==1:
            global time_h
            time_h = 24
            while time_h!= 0:
                time.sleep(360)
                time_h = time_h-1

m=threading.Thread(name='minutes',target=minutes)
s=threading.Thread(name='seconds',target=seconds)
h=threading.Thread(name='hours',target=hours)

m.start()
s.start()
h.start()

Enjoy Programming :-)! 享受编程:-)!

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

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