21番茄网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 21番茄网
查看: 1073|回复: 0

python 倒计时

[复制链接]

646

主题

799

帖子

2686

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2686
发表于 2020-12-7 22:56:01 | 显示全部楼层 |阅读模式
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,自己做了一点修改。

python  倒计时  Python基础语法 1
                               
登录/注册后可看大图


另外一种倒计时的写法:
import time
for i in range(10):
    print("\r离程序退出还剩%s秒" % (9-i), end="")
    time.sleep(1)


python  倒计时  Python基础语法 1
                               
登录/注册后可看大图


另外一种倒计时的写法:
import 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')
来自:https://www.cnblogs.com/zmzzm/articles/11996794.html

python  倒计时  Python基础语法 1
                               
登录/注册后可看大图


另外一种倒计时的写法:
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

python  倒计时  Python基础语法 1
                               
登录/注册后可看大图


另外一种倒计时的写法:
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也可以没有,不影响效果。








上一篇:time时间模块
下一篇:格式符%d、%.2d、%2d、%02d的区别
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|21番茄网 ( 粤ICP备10099428号 ) 奇远富

GMT+8, 2024-4-27 06:22 , Processed in 0.623295 second(s), 34 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表