| import time
def shuru(m):
    try:
        m=int(m)
    except ValueError:
        print('Must be an integer!')
    else:
        while True:
            if m==0:
                break
            for second in range(59,-1,-1):
                time.sleep(1)
                print('{}:{}'.format(m-1,second),end=' \r')
            if second==0:
                m=m-1
        print('时间到了!')
shuru(1)
 说明:
 print('{}:{}'.format(m-1,second),end=' \r')
 上面这句,也可以写成下面这样,最后10秒的计数样式会有细微差别。
 print('\r{}:{}'.format(m-1,second),end=' ')  注意,end的单引号之间要有一个空格。
 
 特别注意的是print函数内的end参数,必须是end=' \r',第1个单引号和反斜线之间,必须要插入1个空白符,否则它的秒数,倒计时到个位数时,会被10位数的数字所覆盖。
 
 \r  转义字符的使用很巧妙,详见:http://www.21fanqie.com/thread-42-1-6.html
 
 来自:https://www.jianshu.com/p/c85439834042,自己做了一点修改。
 
 
 
 另外一种倒计时的写法:
 
 import time
for i in range(10):
    print("\r离程序退出还剩%s秒" % (9-i), end="")
    time.sleep(1)
 
 
 另外一种倒计时的写法:
 
 来自:https://www.cnblogs.com/zmzzm/articles/11996794.htmlimport time
count = 0
a = input('time:')
b = int(a) * 60
while (count < b):
    chazhi = b - count
    print('\r%d 秒'%chazhi,end=' ')
    time.sleep(1)
    count += 1
print('done')
 
 
 另外一种倒计时的写法:
 
 import time
for second in range(120,-1,-1):
    print("%02d:%02d"%(second // 60,second % 60),end=' \r')
    time.sleep(1)
“ // 和 % ”运算符详见:http://www.21fanqie.com/thread-75-1-1.html
 %02d 格式符详见:http://www.21fanqie.com/thread-163-1-1.html
 
 
 
 另外一种倒计时的写法:
 
 import time
task_time = int(input('你觉得自己至少可以专注这个任务多少分钟?输入 N 分钟'))
for t in range(task_time*60,0,-1):
    info = '请专注任务,还要保持专注 ' + str(t) + ' 秒哦!'
    print(info,end="")
    print("\r"*(len(info)*2),end="",flush=True)
    time.sleep(1)
print('你已经专注了 %d 分钟,很棒~再加把劲,完成任务!'%task_time)  
说明:*(len(info)*2)纯属凑数,没有也可照样运行。不过这种写法,有点意思,可以研究一下。flush=True也可以没有,不影响效果。
 
 
 
 
 
 |