The flow of the programs written in any programming language is sequential by default. The first statement in a function is executed first, followed by the second, and so on. There may be a situation when the programmer needs to execute a block of code several times. For this purpose, The programming languages provide various kinds of loops that are able to repeat some particular code numerous numbers of times. Here, we are going to talk about looping statements in Python.
Looping simplifies complicated problems into smooth ones. It allows programmers to modify the flow of the program so that rather than writing the same code, again and again, programmers are able to repeat the code a finite number of times.
In Python, there are three different types of loops: for loop, while loop, and nested loop.
Here, we will read about these different types of loops and how to use them.
The for loop is used in the case where a programmer needs to execute a part of the code until the given condition is satisfied. The for loop is also called a pre-tested loop. It is best to use for loop if the number of iterations is known in advance.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).
for variable in sequence: statements(s)
a = 5 for i in range(0, a): print(i)
0 1 2 3 4
The for loop runs till the value of i is less than a. As the value of i is 5, the loop ends.
The while loop is to be used in situations where the number of iterations is unknown at first. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.
In Python, the while loop executes the statement or group of statements repeatedly while the given condition is True. And when the condition becomes false, the loop ends and moves to the next statement after the loop.
While condition: statement(s)
count = 0 while (count < 5): count = count + 1 print("Flexiple")
Flexiple Flexiple Flexiple Flexiple Flexiple
The loop prints ‘Flexiple’ till the value of count becomes 5 and the condition is False.
The Python programming language allows programmers to use one looping statement inside another looping statement.
#for loop statement for variable in sequence: for variable in sequence: statement(s) statement(s)
for i in range(1, 7): for j in range(i): print(i, end=' ') print()
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6
In this tutorial, we read about different looping statements in Python and their uses. The looping statements are used to repeat a specific block of code various number of times. One can read about other Python concepts here.