Python program to display multiplication table

In this Python example you will learn how to write a python program example to display a multiplication table

Example 1 Using Python for loop

# This program displays the multiplication table of the user's input.

# Get user input for the number to display multiplication table for
number = int(input("Enter a number: "))

# Use a for loop to iterate through 1 to 10 and display the multiplication table
for i in range(1, 11):
    # Multiply the number with each i to get the result
    result = number * i
    # Display the multiplication table in a formatted string
    print(f"{number} x {i} = {result}")

Output

Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Example 2 : Using Python while loop

# Take input from the user
num = int(input("Enter a number: "))

# Initialize counter to 1
i = 1

# Use a while loop to iterate through 1 to 10
while i <= 10:
    # multiply the number with each i
    result = num * i
    # display the result
    print(num, "x", i, "=", result)
    # increment the counter
    i += 1

Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Example 3: Using Python List Comprehension

# Take input from the user
num = int(input("Enter a number: "))

# Use list comprehension to create a list of multiplication results
results = [num * i for i in range(1, 11)]

# Use a for loop to display the multiplication table
for i, result in enumerate(results, start=1):
    print(num, "x", i, "=", result)

Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Here in the program, we use list comprehension to create a list of multiplication results. It multiplies the number entered by the user (num) with each value in the range 1 to 10 using a for loop and list comprehension and stores the results in the results list.

Leave a Comment