In every computer programming language, there is a concept of loops. Loops are the kind of statements that make a statement or a group of statements execute multiple times repetitively. In Python there are two kinds of loops:
In Python the 'for' loop works in two different ways. The one is called sequence based for and the other is called .
It is the basic form of ‘for’ loop in Python. Here we use a variable that changes its value based on a predefined sequence of values. However, it’s not mandatory to have uniform difference between values in the sequence.
Syntax:
Example:
This code will print:
It is another form of for loop. It uses a library function ‘range()’ that creates a list of integer values ranging from a start value to a stop value. The variable used here ranges its values from the start to the stop value as specified by the range function.
Syntax:
Example:
This code will print:
Here if you see, the range started at 12 but it stopped at 14. It did not reach up to 15. Well, this is because of the fundamental behavior of range() function. It ranges from the start value till the (stop - 1) value. Range() function can be called in the following three ways:
A few examples of range() function are:
The ‘while’ loop is a loop that works based on a condition. This loop keeps on iterating as long as the condition written with the ‘while’ statement evaluates as TRUE. When the condition goes false, the control moves on to the next line after the loop body.
Syntax:
Example:
This code will print:
In ‘while’ loop it’s important to have the variable initialized in advance. ‘while’ loop is preferred when the exact number of iterations is not known but the condition on which the loop has to terminate is known.