使用Python编写一个简单的计时器程序
发布时间:2023-12-04 15:15:52
下面是一个使用Python编写的简单计时器程序的代码示例:
import time
class Timer:
def __init__(self):
self.start_time = None
self.end_time = None
def start(self):
if self.start_time is not None:
print("Timer is already running.")
return
self.start_time = time.time()
print("Timer started.")
def stop(self):
if self.start_time is None:
print("Timer is not running.")
return
self.end_time = time.time()
elapsed_time = self.end_time - self.start_time
print(f"Timer stopped. Elapsed time: {elapsed_time:.2f} seconds.")
def reset(self):
self.start_time = None
self.end_time = None
print("Timer reset.")
# 使用例子
timer = Timer()
timer.start()
time.sleep(2) # 暂停2秒钟
timer.stop()
timer.start()
time.sleep(1) # 暂停1秒钟
timer.stop()
timer.reset()
timer.start()
time.sleep(3) # 暂停3秒钟
timer.stop()
这个计时器程序定义了一个Timer类,它有start()、stop()和reset()方法来控制计时器的行为。
在使用例子中,我们首先创建了一个timer实例,并调用start()方法来开始计时。然后使用time.sleep()来模拟一段暂停的时间。接着调用stop()方法来停止计时,并输出经过的时间。
下一次,我们再次调用start()方法开始计时,然后再调用stop()方法停止计时,并输出经过的时间。
最后,我们调用reset()方法重置计时器,然后再次使用start()和stop()方法来进行计时。
以上就是使用Python编写的一个简单的计时器程序,你可以根据自己的需求进行适当的修改和扩展。
