当前位置:嗨网首页>书籍在线阅读

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.

导入 timesubprocess 后,创建变量 timeLeft ,也保存倒计时剩下的秒数❶。它从60开始,或者可以根据需要更改这里的值,甚至通过命令行参数设置它。

while 循环中,显示剩余次数❷,暂停1秒❸,再减少 timeLeft 变量的值❹,然后循环再次开始。只要 timeLeft 大于0,循环就继续。在这之后,倒计时就结束了。