Home  >  Article  >  Backend Development  >  How to implement countdown function in python

How to implement countdown function in python

尚
Original
2019-07-01 10:43:344830browse

How to implement countdown function in python

The following example uses the time module to implement the stopwatch function:

import time
print('按下回车开始计时,按下 Ctrl + C 停止计时。')
while True:
   try:
     input() # 如果是 python 2.x 版本请使用 raw_input() 
        starttime = time.time()
        print('开始')
        while True:
           rint('计时: ', round(time.time() - starttime, 0), '秒', end="\r")
           time.sleep(1)
    except KeyboardInterrupt:
        print('结束')
        endtime = time.time()
        print('总共的时间为:', round(endtime - starttime, 2),'secs')
        break

Test results:

按下回车开始计时,按下 Ctrl + C 停止计时。
开始
计时:  3.0 秒
计时:  5.0 秒
^C结束 6.0 秒
总共的时间为: 6.69 secs

For more Python related technical articles, please visit PythonTutorial column to learn!

The above is the detailed content of How to implement countdown function in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn