We have learnt about strings and lists. Now let us learn about loops. We use loops when we have to perform a particular action repeatedly.
There are two types of loops in python- For loop and while loop.
- For loops iterate over a given fixed number of elements in a fixed definite sequence.
In the first example, fruits is a list which consists of 4 fruits. It has 4 elements. We assign the variable i to each element in the list “fruits”. When we execute a print statement, each element in the list is printed. The same applies to the second example. In the second example, we use a list called mymarks which contains 6 numbers. The variable mark is assigned to each element in the list “mymarks”. When print statement is executed within the loop, each element is printed one by one.
- For loops also use range( ) to iterate. The range( ) function is used to generate a sequence of numbers. For example, range(10) generates numbers from 0 to 9. It can also be written in this way in which the start, stop and step size are specified as range(start,stop,stepsize). Step size is 1 by default.
In the above examples, you can see the use of the range( ) function.
- While loops perform a particular action repeatedly as long as a certain boolean condition is satisfied. When the condition becomes false the line immediately after the loop is executed.
The above example is a simple example for a while loop. In this example, we define a variable num and give it a value of 5. Then we initialize a while loop that checks for the condition if num is less than 12. As long as num is less than 12, we keep incrementing the value of num by 1. Hence 5,6,7,8,9,10 and 11 are printed. The control enters the loop 7 times. The last number printed is 11 since it is just less than 12.
Remember: while(1) or while (True) condition will result in an infinite loop since the condition is always satisfied. We will see this later in the programs.
- “break” and “continue” statements are used in loops. “break” is used to exit a for loop or while loop. “continue” is used to skip the current function block and return to the next iteration in the same for or while loop. Let us see how they work in the following examples.
- Nested loops are nothing but loops within loops. An example of a nested loop is shown below.
In this example we print multiplication tables for 1,2 and 3.