Python Program to Print the Multiplication Table of a Number
Beginner Numbers
Prints the multiplication table of a number from 1 to 10, one line per multiple, with a for loop.
A multiplication table, or times table, lists a number multiplied by 1, 2, 3 and so on, usually up to 10. The table of 7 starts 7, 14, 21 and ends at 70. It's often the first loop a learner writes: the same line printed ten times, with one number changing each time.
Program
def print_table(number):
"""Print number x 1 up to number x 10, one per line."""
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
print_table(7)
Open in the editor Download multiplication_table.py
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
How it works
Step through the program line by line: each step below shows up as its line runs.
-
range(1, 11)gives the numbers 1 to 10. A range stops before its end, so it needs 11 to include 10. The for loop runs once for each, withiholding the number. - Each time round, the f-string puts the number,
iand their product into one line, so 7 and 3 print7 x 3 = 21. - The program prints the table of 7. The function prints its own lines and returns nothing, so the
call has no
print()around it: that would print an extraNoneat the end.
Other ways to write it
With a while loop
A while loop needs its own counter: it starts at 1, and the loop adds 1 to it each time round until it passes 10.
def print_table(number):
i = 1
while i <= 10:
print(f"{number} x {i} = {number * i}")
i += 1
print_table(3)Try it yourself
- Print the table of 12, or of a negative number such as -4.
- Make the table go up to 20: change the
11inrange(1, 11), or give the function a second argument for where to stop. - Line up the columns by giving each number a width in the f-string:
f"{number} x {i:2} = {number * i:3}". - Call the function in a loop to print the tables of 2 to 5, one after another.