In the previous article we have seen the Calculator implementation , now we will go through the concept of loops in Python. Looping structures are instrumental in reducing the repeated statements or complexity of code. Let us look at the example of multiplication tables. We need to write a program that accepts a user input number and then displays the number’s respective multiplication table. For example, if a user provides 3 as the number it would return 3,6,9,12,15,18,21,24,27,30. If the user instead provides the number 5 to the program it would return 5,10,15,20,25,30,35,40,45,50.
Implementation of Loop to handle multiplication program
Let us look at an approach to handle multiplication program without the involvement of loops:
n=int (print"Enter a number: "))
print(n)
print(n*2)
print(n*3)
print(n*4)
print(n*5)
print(n*6)
print(n*7)
print(n*8)
print(n*9)
print(n*10)
Output:
Enter a number: 3
3
6
9
12
15
18
21
24
27
30
What are the limitations of this program? We can see the program itself is quite lengthy, and much of the program revolves around repeating the same bits of logic. The program is also quite limited in scope, imagine a user specifies that they want more than just 10 multiples but the same certain amount of multiples which are directly specified by the user.
How do we write a program free from the above limitations? To write a much more effective and capable program we would definitely need to involve looping statements. Loops and looping statements exist in some form in all commonly used programming languages and they allow us to repeat the same bits of statement as and when needed. Thus loops have the following utility in programming languages:
Uses of loops in programming languages
- For doing a certain task multiple times(In repetition): Frequently programming languages run into situations where code can be more effectively written or reduced in complexity, limiting the repeated blocks of statements or mundane tasks. Loops enable us to write much more efficient programs which are processed better.
- For traversing through collections(Lists, Tuples, Sets, etc): To work with iterable data types, often the involvement of loops is required to collectively go through the elements, to perform operation on their elements or for handling specific items in them.
- Running services in systems frequently: Operating systems involve various tasks or services constantly running in the background to perform routine tasks or to ensure the working of the system. These kind of services operate by loop logic constrained by time requirements.
In the next article we will discuss the function and usage of while-loop in Python.