This program generates a multiplication table from 0 × 0 to 12 × 12. While simple, it provides a useful demonstration of nested loops.
When you run multiplicationtable.py, the output will look like this:
Multiplication Table, by Al Sweigart [email protected]
| 0 1 2 3 4 5 6 7 8 9 10 11 12
--+---------------------------------------------------
0| 0 0 0 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9 10 11 12
2| 0 2 4 6 8 10 12 14 16 18 20 22 24
3| 0 3 6 9 12 15 18 21 24 27 30 33 36
4| 0 4 8 12 16 20 24 28 32 36 40 44 48
5| 0 5 10 15 20 25 30 35 40 45 50 55 60
6| 0 6 12 18 24 30 36 42 48 54 60 66 72
7| 0 7 14 21 28 35 42 49 56 63 70 77 84
8| 0 8 16 24 32 40 48 56 64 72 80 88 96
9| 0 9 18 27 36 45 54 63 72 81 90 99 108
10| 0 10 20 30 40 50 60 70 80 90 100 110 120
11| 0 11 22 33 44 55 66 77 88 99 110 121 132
12| 0 12 24 36 48 60 72 84 96 108 120 132 144
Line 9 prints the top row of the table. Notice that it sets a large enough distance between the numbers to accommodate products that are a maximum of three digits long. Since this is a 12 × 12 multiplication table, this spacing can fit the largest product, 144. If you want to create a larger table, you may need to increase the spacing for the columns as well. Keep in mind that the standard terminal window is 80 columns wide and 24 rows tall, so you cannot create much larger multiplication tables without having the rows wrap around the right edge of the window.
1. """Multiplication Table, by Al Sweigart [email protected]
2. Print a multiplication table.
3. This code is available at https://nostarch.com/big-book-small-python-programming
4. Tags: tiny, beginner, math"""
5.
6. print('Multiplication Table, by Al Sweigart [email protected]')
7.
8. # Print the horizontal number labels:
9. print(' | 0 1 2 3 4 5 6 7 8 9 10 11 12')
10. print('--+---------------------------------------------------')
11.
12. # Display each row of products:
13. for number1 in range(0, 13):
14.
15. # Print the vertical numbers labels:
16. print(str(number1).rjust(2), end='')
17.
18. # Print a separating bar:
19. print('|', end='')
20.
21. for number2 in range(0, 13):
22. # Print the product followed by a space:
23. print(str(number1 * number2).rjust(3), end=' ')
24.
25. print() # Finish the row by printing a newline.
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.
range(0, 13)
on line 13 to range(0, 80)
?range(0, 13)
on line 13 to range(0, 100)
?