Countdown

Tags: tiny, artistic

This program displays a digital timer that counts down to zero. Rather than render numeric characters directly, the sevseg.py module from Project 64, “Seven-Segment Display Module,” generates the drawings for each digit. You must create this file before the Countdown program can work. Then, set the countdown timer to any number of seconds, minutes, and hours you like. This program is similar to Project 19, “Digital Clock.

countdown.py
 1"""Countdown, by Al Sweigart al@inventwithpython.com
 2Show a countdown timer animation using a seven-segment display.
 3Press Ctrl-C to stop.
 4More info at https://en.wikipedia.org/wiki/Seven-segment_display
 5Requires sevseg.py to be in the same folder.
 6This code is available at https://nostarch.com/big-book-small-python-programming
 7Tags: tiny, artistic"""
 8
 9import sys, time
10import sevseg  # Imports our sevseg.py program.
11
12# (!) Change this to any number of seconds:
13secondsLeft = 30
14
15try:
16    while True:  # Main program loop.
17        # Clear the screen by printing several newlines:
18        print('\n' * 60)
19
20        # Get the hours/minutes/seconds from secondsLeft:
21        # For example: 7265 is 2 hours, 1 minute, 5 seconds.
22        # So 7265 // 3600 is 2 hours:
23        hours = str(secondsLeft // 3600)
24        # And 7265 % 3600 is 65, and 65 // 60 is 1 minute:
25        minutes = str((secondsLeft % 3600) // 60)
26        # And 7265 % 60 is 5 seconds:
27        seconds = str(secondsLeft % 60)
28
29        # Get the digit strings from the sevseg module:
30        hDigits = sevseg.getSevSegStr(hours, 2)
31        hTopRow, hMiddleRow, hBottomRow = hDigits.splitlines()
32
33        mDigits = sevseg.getSevSegStr(minutes, 2)
34        mTopRow, mMiddleRow, mBottomRow = mDigits.splitlines()
35
36        sDigits = sevseg.getSevSegStr(seconds, 2)
37        sTopRow, sMiddleRow, sBottomRow = sDigits.splitlines()
38
39        # Display the digits:
40        print(hTopRow    + '     ' + mTopRow    + '     ' + sTopRow)
41        print(hMiddleRow + '  *  ' + mMiddleRow + '  *  ' + sMiddleRow)
42        print(hBottomRow + '  *  ' + mBottomRow + '  *  ' + sBottomRow)
43
44        if secondsLeft == 0:
45            print()
46            print('    * * * * BOOM * * * *')
47            break
48
49        print()
50        print('Press Ctrl-C to quit.')
51
52        time.sleep(1)  # Insert a one-second pause.
53        secondsLeft -= 1
54except KeyboardInterrupt:
55    print('Countdown, by Al Sweigart al@inventwithpython.com')
56    sys.exit()  # When Ctrl-C is pressed, end the program.)

https://inventwithpython.com/bigbookpython/project14.html