Rainbow is a simple program that shows a colorful rainbow traveling back and forth across the screen. The program makes use of the fact that when new lines of text appear, the existing text scrolls up, causing it to look like it’s moving. This program is good for beginners, and it’s similar to Project 15, “Deep Cave.”
Figure 58-1 shows what the output will look like when you run rainbow.py.
This program continuously prints the same rainbow pattern. What changes is the number of space characters printed to the left of it. Increasing this number moves the rainbow to the right, and decreasing it moves the rainbow to the left. The indent
variable keeps track of the number of spaces. The indentIncreasing
variable is set to True
to note that indent
should increase until it reaches 60
, at which point it changes to False
. The rest of the code decreases the number of spaces. Once it reaches 0
, it changes back to True
again to repeat the zigzag of the rainbow.
1. """Rainbow, by Al Sweigart [email protected]
2. Shows a simple rainbow animation. Press Ctrl-C to stop.
3. This code is available at https://nostarch.com/big-book-small-python-programming
4. Tags: tiny, artistic, bext, beginner, scrolling"""
5.
6. import time, sys
7.
8. try:
9. import bext
10. except ImportError:
11. print('This program requires the bext module, which you')
12. print('can install by following the instructions at')
13. print('https://pypi.org/project/Bext/')
14. sys.exit()
15.
16. print('Rainbow, by Al Sweigart [email protected]')
17. print('Press Ctrl-C to stop.')
18. time.sleep(3)
19.
20. indent = 0 # How many spaces to indent.
21. indentIncreasing = True # Whether the indentation is increasing or not.
22.
23. try:
24. while True: # Main program loop.
25. print(' ' * indent, end='')
26. bext.fg('red')
27. print('##', end='')
28. bext.fg('yellow')
29. print('##', end='')
30. bext.fg('green')
31. print('##', end='')
32. bext.fg('blue')
33. print('##', end='')
34. bext.fg('cyan')
35. print('##', end='')
36. bext.fg('purple')
37. print('##')
38.
39. if indentIncreasing:
40. # Increase the number of spaces:
41. indent = indent + 1
42. if indent == 60: # (!) Change this to 10 or 30.
43. # Change direction:
44. indentIncreasing = False
45. else:
46. # Decrease the number of spaces:
47. indent = indent - 1
48. if indent == 0:
49. # Change direction:
50. indentIncreasing = True
51.
52. time.sleep(0.02) # Add a slight pause.
53. except KeyboardInterrupt:
54. sys.exit() # When Ctrl-C is pressed, end the program.
Try to find the answers to the following questions. Experiment with some modifications to the code and rerun the program to see what effect the changes have.
False
on line 44 to True
?bext.fg()
calls to 'random'
?