30-第1步_倒计时
第1步:倒计时
这个程序需要使用 time
模块的 time.sleep()
函数、 subprocess
模块的 subprocess. Popen()
函数。输入以下代码并保存为countdown.py:
#! python3
# countdown.py - A simple countdown script.
import time, subprocess
❶ timeLeft = 60
while timeLeft > 0:
❷ print(timeLeft, end='')
❸ time.sleep(1)
❹ timeLeft = timeLeft - 1
# TODO: At the end of the countdown, play a sound file.
导入 time
和 subprocess
后,创建变量 timeLeft
,也保存倒计时剩下的秒数❶。它从60开始,或者可以根据需要更改这里的值,甚至通过命令行参数设置它。
在 while
循环中,显示剩余次数❷,暂停1秒❸,再减少 timeLeft
变量的值❹,然后循环再次开始。只要 timeLeft
大于0,循环就继续。在这之后,倒计时就结束了。