[英]Creating a Stopwatch progam for Python 3.3 only in IDLE
我有一個任務需要創建秒表,但僅用於IDLE。 這是我到目前為止的內容,我不確定如何將時間轉換為正常時間。
import time
start = 0
def stopwatch():
while True:
command = input("Type: start, stop, reset, or quit: \n")
if (command == "quit"):
break
elif (command == "start"):
start = time.time()
print(start)
stopwatch2()
elif (command == "stop"):
stopwatch()
elif (command == "reset'"):
stopwatch()
else :
break
def stopwatch2():
while True:
command = input("Type: stop, reset, or quit: \n")
if (command == "quit"):
break
elif (command == "stop"):
total = time.time() - start
print(total)
stopwatch()
elif (command == "reset'"):
stopwatch()
else:
break
stopwatch()
謝謝你的幫助!
您可以使用datetime.timedelta()
:
import datetime
print(datetime.timedelta(seconds=total))
例如:
In [10]: print datetime.timedelta(seconds=10000000)
115 days, 17:46:40
像這樣思考...空閑實際上與我一直在做的交互式python解釋器中的編碼沒有什么不同(嗯,我使用ipython)。
將秒表想像成一個對象。 它有什么功能? 諸如開始,停止,重置之類的事情。
這可能不是解決問題的最有效方法,但這是我要做的。
>>> import time
>>> class StopwatchException:
pass
>>> class IsRunningException(StopwatchException):
pass
>>> class NotRunningException(StopwatchException):
pass
>>> class Stopwatch():
def __init__(self):
self._times = []
self._is_running = False
def start(self):
if self._is_running:
raise IsRunningException
self._is_running = True
tracker = {
'start': time.time(),
'stop': None,
}
self._times.append(tracker)
def stop(self):
if not self._is_running:
raise NotRunningException
tracker = self._times[-1]
# the dict is mutable, and tracker is a shallow copy
tracker['stop'] = time.time()
#print(self._times[-1])
self._is_running = False
def reset(self):
if self._is_running:
raise IsRunningException
self._times = []
def total(self):
if self._is_running:
raise IsRunningException
total = 0.0
for t in self._times:
total += t['stop'] - t['start']
return total
>>> s = Stopwatch()
>>> s.start()
>>> s.stop()
>>> s.total()
6.499619960784912
>>> s.reset()
>>> s.total()
0.0
對我來說,任何時候只要要對現實世界對象或“事物”建模,OOP都是最有意義的。 這是程序中每個元素的簡單參數:
基本的秒表類實際上只需要實例變量。 一個變量存儲每個開始/停止時間(允許以后計算),一個變量存儲秒表的“狀態”(開/關或運行/停止)。
start
然后,我們需要將其狀態設置為運行,並將時間存儲在
self._times
。 我選擇使用局部變量,並將每個時間對存儲為帶有“ start”和“ stop”鍵的字典。 我選擇字典是因為它是可變的。 您可能還具有一個列表,其中索引0為開始時間,索引1為停止時間。 您不能為此使用元組,因為元組是不可變的。 另外,“臨時”變量不是必需的,但出於可讀性考慮,我使用了它。
stop
然后,我們將狀態設置為“已停止”(使用布爾
self._is_running
)並存儲我們的停止時間,類似於對start
所做的操作。 我認為將布爾值設置為開始還是結束都沒有關系,盡管我選擇將其設置為start函數的開始和stop函數的結束,以便時間不包括計算布爾值所需的時間。更新布爾變量(即使這是一項瑣碎的任務,但在更復雜的程序中可能會更加復雜)。
reset
self._times
設置為空列表。 total
self._times
每個列表項,並計算停止和開始之間的差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.