In the previous article we explore the For Loop structure, now let us take a look at an example case of printing Multiplication Table of a Number in Python. If a user provides the number 3, we return 3, 6, 9, 12, 15, 18, 21, 27 and 30. If the number specified was 5 instead it would return 5, 10, 15, 20, 25, 30, 35, 40, 45, 50.
Implementation of Multiplication Table of a Number in Python using while..loop
n=int(input("Enter n:"))
i=1
while i <= 10:
print(i*n)
i=i+1
Output:
Enter n:5
5
10
15
20
25
30
35
40
45
50
The program accepts an input number from the user, initializes a count variable i. The program than prints the multiplication results and incrementally also increases the count of the variable i as it progresses to the next number. The while loop structure checks whether the condition of the count variable being less than or equal to 10 before the program is executed.
However what if we would like to provide more options to the user besides setting a value of 10?
n=int(input("Enter n:"))
m=int(input("Enter m:"))
i=1
while i <= m:
print(i*n)
i=i+1
Output:
Enter n:5
Enter m:20
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
Implementation of Multiplication Table of a Number in Python using For .. loop
n=int(input("Enter a number:"))
for i in range(1,11):
print(i*n)
#Note range(1,x) gives
#number 1,2,3,....x-1
Output:
Enter a number:5
5
10
15
20
25
30
35
40
45
50
We use the range function to define or limit the range of the multiplication table length. Suppose we want to print the table according to the length defined by the user:
n=int(input("Enter a number:"))
m=int(input("Enter a number:"))
for i in range(1, m+1):
print(i*n)
#Note range(1,x) gives
#number 1,2,3,....x-1
Output:
Enter a number:6
Enter a number:14
6
12
18
24
30
36
42
48
54
60
66
72
78
84
This program takes two input values from the user that is n and m. The variable m specifies the limit or extent to which the loop occurs.
Hence, we have seen the multiple ways or approaches to the Multiplication Table Program in python, in the next article we will explore the use of the break function and it’s utility within looping statements or structures.