簡體   English   中英

我如何每x秒重復一次程序,持續x秒(在我的情況下,每3秒重復30秒)

[英]How can I repeat a program every x seconds for x seconds(in my case, every 3 seconds for 30 seconds)

我的編程老師給我分配了一個簡單的任務,即創建一個程序,該程序每3秒隨機產生一個1-100之間的數字,持續30秒。 到目前為止,這是我的程序:

import random
import time

while True:
    print(random.randint(0,100))
    time.sleep(3)

目前,它僅每3秒鍾無限打印一次。 我希望它僅重復30秒。

感謝您的考慮!

import random
import time
a=time.clock()

while ((time.clock()-a)<30):
    print(random.randint(0,100))
    time.sleep(3)

這是一項任務,因此我們無法為您解決。 但是,我們可以指導你正確的模塊來使用,這是sched記錄在這里https://docs.python.org/3.6/library/sched.html

利用time.time()函數。 自1970年1月1日00:00:00(UTC)起,它以秒為單位。

import random
import time

counter = 30
start_time = time.time()
while time.time() - start_time < counter:
    print(random.randint(0,100))
    time.sleep(3)

使用如下的for range循環:

import time
import random
a=time.clock()
for x in range(10):
    print(random.randint(1,100))
    time.sleep(3)

暫無
暫無

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

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