Python用time,设计程序,显示20秒倒计时Python用time,设计程序,显示20秒倒计?

Python09

Python用time,设计程序,显示20秒倒计时Python用time,设计程序,显示20秒倒计?,第1张

回答会自动过滤缩进,需要按照上图调整语法缩进,下方是代码

import time

# 设置倒计时时间(单位:秒)

countdown_time = 20

# 开始循环

while countdown_time >0:

# 打印当前倒计时时间

print(countdown_time)

# 等待 1 秒

time.sleep(1)

# 倒计时时间减 1

countdown_time -= 1

# 倒计时结束

print("倒计时结束!")

我想在Python中创建一个倒计时,我想用非常简单的方法来创建。我看了几个视频,但没有找到合适的解决方案。

这是我现在正在使用的代码。

import time

def countdown(t):

while t:

mins, secs = divmod(t, 60)

timer = '{:02d}:{:02d}'.format(mins, secs)

print(timer, end="\r")

time.sleep(1)

t -= 1

print('Time Over!!!!')

t = input("Enter the time in seconds: ")

countdown(int(t))

解决方案1

问题是,当你睡眠1秒的时候,并不是精确的1秒,理论上说,在足够长的时间内,错误可能会传播,以至于你可能会打印出一个错误的时间。为了纠正这一点,你的代码需要在它的循环中实际检查从程序开始运行以来实际经过了多少时间,并使用它来计算t的新值是多少,而且它应该经常这样做,以便倒计时顺利进行。比如说。

import time

def countdown(t):

start_time = time.time()

start_t = t

# compute accurate new t value aprroximately every .05 seconds:

while t >0:

mins, secs = divmod(t, 60)

timer = '{:02d}:{:02d}'.format(mins, secs)

print(timer, end="\r")

time.sleep(.05) # finer timing

now = time.time()

elapsed_time = int(now - start_time) # truncated to seconds

t = start_t - elapsed_time

print('Time Over!!!!')

t = input("Enter the time in seconds: ")

countdown(int(t))

参考: How to make a countdown

用python实现计时器功能,代码如下:

''' Simple Timing Function.

This function prints out a message with the elapsed time from the

previous call. It works with most Python 2.x platforms. The function

uses a simple trick to store a persistent variable (clock) without

using a global variable.

'''

import time

def dur( op=None, clock=[time.time()] ):

if op != None:

duration = time.time() - clock[0]

print '%s finished. Duration %.6f seconds.' % (op, duration)

clock[0] = time.time()

# Example

if __name__ == '__main__':

import array

dur() # Initialise the timing clock

opt1 = array.array('H')

for i in range(1000):

for n in range(1000):

opt1.append(n)

dur('Array from append')

opt2 = array.array('H')

seq = range(1000)

for i in range(1000):

opt2.extend(seq)

dur('Array from list extend')

opt3 = array.array('H')

seq = array.array('H', range(1000))

for i in range(1000):

opt3.extend(seq)

dur('Array from array extend')

# Output:

# Array from append finished. Duration 0.175320 seconds.

# Array from list extend finished. Duration 0.068974 seconds.

# Array from array extend finished. Duration 0.001394 seconds.