python秒表_使用Python创建秒表

本文介绍了如何使用Python实现一个简单的秒表功能。秒表在用户按下ENTER键时开始计时,按下CTRL+C时停止,并通过计算两个时间点的差值得到所用时间。主要依赖于time模块的time()函数来获取时间。
摘要由CSDN通过智能技术生成

python秒表

The task is to create a stopwatch.

任务是创建一个秒表。

In the below program, the stopwatch will be started when you press the ENTER key and stopped when you press the CTRL+C key.

在下面的程序中,秒表将在您按ENTER键时启动,而在您按CTRL + C键时停止。

Logic: To run the stopwatch (count the time), we are writing the code in an infinite loop, start time will be saved in start_time variable as you press the ENTER and when you press the CTRL + C a KeyboardInterrupt exception will generate and we will again get the time, which will be considered as end_time. Now, to calculate the difference – we will simply subtract the time from end_time to start_time.

逻辑:要运行秒表(计算时间),我们正在无限循环中编写代码,当您按ENTER键时,开始时间将保存在start_time变量中;当您按CTRL + C 键时,将生成KeyboardInterrupt异常,并且将再次获得时间,该时间将被视为end_time 。 现在,要计算差异–我们只需将时间从end_time减去start_time即可 。

To get the time in seconds, we are using time() function of the time module. So, you need to import the time module first.

为了获得以秒为单位的时间,我们使用时间模块的time()函数 。 因此,您需要首先导入时间模块。

秒表的Python代码 (Python code for a stopwatch)

# Python code for a stopwatch

# importing the time module 
import time

print("Press ENTER to start the stopwatch")
print("and, press CTRL + C to stop the stopwatch")

# infinite loop
while True:
    try:
        input() #For ENTER
        start_time = time.time()
        print("Stopwatch started...")
        
    except KeyboardInterrupt:
        print("Stopwatch stopped...")
        end_time = time.time()
        print("The total time:", round(end_time - start_time, 2),"seconds")
        break # breaking the loop

Output

输出量

Press ENTER to start the stopwatch
and, press CTRL + C to stop the stopwatch

Stopwatch started...
^CStopwatch stopped...
The total time: 15.81 seconds

By using the above code, we can create a stop watch, to practice more programs, visit – python programs.

通过使用上面的代码,我们可以创建一个秒表,以练习更多程序,请访问python程序

翻译自: https://www.includehelp.com/python/create-a-stopwatch-using-python.aspx

python秒表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值