![](/img/trans.png)
[英]which of these for-loops is more efficient/the better way to code the loop
[英]Is there a better way to loop code?
我正在自學python,並嘗試編寫代碼以在特定時間打開CD驅動器。 出於測試的原因,我一直在使用time.clock(),因為它只使用數字,但是我想使用time.ctime()以便程序在特定時間運行。 這是我到目前為止的代碼。
import time
import ctypes
if(time.clock()==10):
ctypes.windll.winmm.mciSendStringW("set cdaudio door open",
None, 0, None)
for x in range(10**100):
print(x)
if(20>time.clock()>10):
ctypes.windll.winmm.mciSendStringW("set cdaudio door open",
None, 0, None)
quit()
我正在使用print(x)函數監視代碼,並且將范圍設置得足夠高,以使其在達到門應該打開的秒數之前不會停止。
代替for x in range(10**100):
您可以使用
while True:
# do stuff forever
該循環將一直持續到您明確break
(或返回函數,引發異常或退出程序等)為止。
time.ctime()
返回一個字符串,該字符串與給定時間進行比較time.ctime()
。 相反,我建議使用datetime模塊
go_time = datetime.datetime(2014, 9, 3, 12, 30)
while True:
now = datetime.datetime.now()
if now >= go_time:
# open the draw etc...
quit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.