Python program to display multiplication table

In this program we will learn how to display the multiplication table of a number entered by a user. For example if the user enters 7, then the output should be –

7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70

To understand this example you must know the following topics in python programming –

  • Input and int functions.
  • Conditional statements.
  • Loops.

Program

mynum = int(input("Please enter a number"))
i = 1
if mynum == 0:
    print("Enter a number greater than zero")
elif mynum < 0:
    print("Enter a positive number")
else:
    while i <= 10:
        result = mynum * i
        print(mynum, "*", i, "=", result)
        i += 1

Output

Please enter a number4

4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40

Explanation

  • First of all we have declared a variable named mynum and we are storing the number given by the user in this variable.(I’ve already explained the use of input and int functions in the previous programs, that is why i am not repeating it again.)
  • Then we have declared another variable named ‘i’ and initialized it with 1. This variable would be used to execute our loop. Next we have used the if …. elif …. else conditional statements for different cases. As we have allowed the user to enter an integer number, the user could enter a negative number or even 0. But we need a positive non zero integer.
  • In the if statement, we are checking whether the number is zero. If the condition is true (If the user enters 0), the program will terminate with a message “Enter a number greater than zero”.
  • In the elif statement we are checking whether the number is negative. If the condition is true (If the user enters a negative number), the program will terminate by displaying a message that says “Enter a positive number”.
  • If the conditions of ‘if’ and ‘elif’ statements become false (If the number is neither 0 nor negative), the else statement would execute. In the else statement we are executing a loop that would run from 1 to 10. Inside the loop we have declared a variable named result in which we are storing the multiplication of mynum and i (For every iteration of the loop). For example if the value of mynum is 7, then for the first iteration of the loop the product will be 7 * 1, i.e, 7, for the second iteration of the loop, the product will be 7 * 2, i.e., 14 and so on until the value of i becomes 10. With every iteration we are also displaying the result with a formatted string.

Making this program with ‘for’ loop

mynum = int(input("Please enter a number"))
if mynum == 0:
    print("Enter a number greater than zero")
elif mynum < 0:
    print("Enter a positive number")
else:
    for i in range(1, 11):
        result = mynum * i
        print(mynum, "*", i, "=", result)