在Python中实现倒计时功能可使用如下代码:

# import the time module
import time

def countdown(t):
    '''define the countdown function'''
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1
    print('Time out!!')
# function call
countdown(60)

  • divmod(a,b)函数返回商和余数,例如divmod(8,3)返回(2,2)。

  • ‘{:02d}’.format(a)返回a,a至少是两位数(也可以三位,四位…)位数不够左边补零,例如’{:02d}’.format(12)返回12,’{:02d}’.format(120) 返回120,’{:02d}’.format(1) 返回01。

  • end=”\r” 使每次print都覆盖上一次的print

  • time.sleep(1) 使程序暂停1s,以此起到倒计时的效果

本文地址:https://blog.csdn.net/weixin_38484333/article/details/110914658