簡體   English   中英

你如何讓兩個函數在python中並行工作?

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

我是蟒蛇新手並且正在我的學校上課,我接受了制作一個從1或2小時倒計時的作業的作業,並且還顯示了整個時間的分鍾和小時。 我開始做代碼並定義了2個函數,秒和分鍾。 秒數從60秒開始倒數,分鍾完成同樣的事情,除了從1分鍾開始,我分別嘗試了它們並且他們工作了,然后我一起嘗試了它們,我無法讓它們並排工作。 如果我只是使用倒計時的變量,我怎樣才能讓他們這樣做呢? 任何幫助表示贊賞。

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`

此外,縮進可能會搞砸。

因為一分鍾有六十秒。 您無需單獨計算它們。 只計算總秒數並除以60以顯示分鍾數,然后以模60來顯示秒數。

我認為您的程序需要對線程進行大量更改

這個鏈接可以幫助你:-)

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

您想要的完整計划

    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()

享受編程:-)!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM