这个程序显示一个数字计时器,倒计时到零。第六十四个项目的sevseg.py模块“七段显示模块”为每个数字生成图形,而不是直接呈现数字字符。您必须先创建这个文件,倒计时程序才能运行。然后,将倒计时设置为你喜欢的任何秒数、分钟数和小时数。这个程序类似于项目 19,“数字钟。”
当您运行countdown.py时,输出将如下所示:
__ __ __ __ __ __
| | | | * | | | | * __| |__|
|__| |__| * |__| |__| * |__ __|
Press Ctrl-C to quit.运行import sevseg之后,您可以调用sevseg.getSevSegStr()函数来获得一个包含七个段数字的多行字符串。然而,倒计时程序需要在时、分、秒之间显示一个由星号组成的冒号。这需要用splitlines()方法将这些数字的三行多行字符串分割成三个单独的字符串。
"""Countdown, by Al Sweigart email@protected
Show a countdown timer animation using a seven-segment display.
Press Ctrl-C to stop.
More info at https://en.wikipedia.org/wiki/Seven-segment_display
Requires sevseg.py to be in the same folder.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, artistic"""
import sys, time
import sevseg # Imports our sevseg.py program.
# (!) Change this to any number of seconds:
secondsLeft = 30
try:
while True: # Main program loop.
# Clear the screen by printing several newlines:
print('\n' * 60)
# Get the hours/minutes/seconds from secondsLeft:
# For example: 7265 is 2 hours, 1 minute, 5 seconds.
# So 7265 // 3600 is 2 hours:
hours = str(secondsLeft // 3600)
# And 7265 % 3600 is 65, and 65 // 60 is 1 minute:
minutes = str((secondsLeft % 3600) // 60)
# And 7265 % 60 is 5 seconds:
seconds = str(secondsLeft % 60)
# Get the digit strings from the sevseg module:
hDigits = sevseg.getSevSegStr(hours, 2)
hTopRow, hMiddleRow, hBottomRow = hDigits.splitlines()
mDigits = sevseg.getSevSegStr(minutes, 2)
mTopRow, mMiddleRow, mBottomRow = mDigits.splitlines()
sDigits = sevseg.getSevSegStr(seconds, 2)
sTopRow, sMiddleRow, sBottomRow = sDigits.splitlines()
# Display the digits:
print(hTopRow + ' ' + mTopRow + ' ' + sTopRow)
print(hMiddleRow + ' * ' + mMiddleRow + ' * ' + sMiddleRow)
print(hBottomRow + ' * ' + mBottomRow + ' * ' + sBottomRow)
if secondsLeft == 0:
print()
print(' * * * * BOOM * * * *')
break
print()
print('Press Ctrl-C to quit.')
time.sleep(1) # Insert a one-second pause.
secondsLeft -= 1
except KeyboardInterrupt:
print('Countdown, by Al Sweigart email@protected')
sys.exit() # When Ctrl-C is pressed, end the program.) 在输入源代码并运行几次之后,尝试对其进行实验性的修改。你也可以自己想办法做到以下几点:
- 提示用户输入开始倒计时的时间。
- 让用户输入在倒计时结束时显示的消息。
试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。
- 如果把第 13 行的
secondsLeft = 30改成secondsLeft = 30.5会怎么样? - 如果把第 30、33、36 行的
2改成1会怎么样? - 如果把 52 行的
time.sleep(1)改成time.sleep(0.1)会怎么样? - 如果把 53 行的
secondsLeft -= 1改成secondsLeft -= 2会怎么样? - 如果删除或注释掉第 18 行的
print('\n' * 60)会发生什么? - 如果删除或注释掉第 10 行的
import sevseg,会得到什么错误信息?
