利用Python控制台实现简单的计时器
发布时间:2023-12-28 21:55:17
要实现一个简单的计时器,可以使用Python的time模块。下面是一个使用Python控制台实现计时器的示例代码:
import time
class Timer:
def __init__(self):
self.is_running = False
self.start_time = 0
self.end_time = 0
def start(self):
if self.is_running:
print("Timer is already running.")
else:
self.is_running = True
self.start_time = time.time()
print("Timer started.")
def stop(self):
if not self.is_running:
print("Timer is not running.")
else:
self.is_running = False
self.end_time = time.time()
elapsed_time = self.end_time - self.start_time
print("Timer stopped. Elapsed time: {:.2f} seconds.".format(elapsed_time))
def reset(self):
self.is_running = False
self.start_time = 0
self.end_time = 0
print("Timer reset.")
# 使用例子
timer = Timer()
while True:
command = input("Enter 'start', 'stop', 'reset' or 'exit': ")
if command == "start":
timer.start()
elif command == "stop":
timer.stop()
elif command == "reset":
timer.reset()
elif command == "exit":
break
else:
print("Invalid command.")
上述示例代码定义了一个Timer类,其包含三个方法:start用于开始计时,stop用于停止计时并显示经过的时间,reset用于重置计时器。
在使用例子中,我们创建了一个Timer对象,然后在一个循环中等待用户输入命令。用户可以输入"start"开始计时,输入"stop"停止计时并显示经过的时间,输入"reset"重置计时器,输入"exit"退出程序。用户输入其他命令时将显示"Invalid command."。
使用这个计时器,你可以在Python控制台中方便地计时不同的操作,或者用于测试代码的执行时间。
