I'm a software developer with a great interest in data analysis and statistics.
Looping constructs in any programming language are used to perform a sequence of steps repeatedly for a given number of times. Python allows two types of loops: the for loop and the while loop. It is also possible to add a loop in another loop and create a nested loop in Python.
The For Loop
While iterating over a tuple or list, we can either use indices and write a traditional for loop that is similar to the one found in C/C++ or write a for-each-sequence loop similar to that in Java. Let us learn more about for loops.
Iterating Over Building Blocks of a Sequence
In the first for loop, we take the string ‘HelloWorld!’ sequence and iterate over it using iteration variable. In general, the syntax of this type of for loop can be expressed as:
The first two for loops show how letters in a string and words in a list representing a phrase are treated as individual building blocks of the sequence.
The output for the above program will be:
Printing letters of string in each line... H e l l o W o r l d ! Printing words in the rhyme in each line... Mary Had A Little Lamb ...Reached the end...
This type of for loop can be applied in case of a tuple or a dictionary as well. The code below demonstrates how to iterate over a dictionary considering the keys or key-value pairs as the building blocks of the sequence.
In the first for loop, we iterate over the dictionary using key alone. In the second for loop, both key and value are used as iteration variables to iterate over the items in the dictionary named "studentDict". Note that it is not mandatory to mention the name as ‘key’ and ‘value’ always in the for loop and to demonstrate it, we have used foo and bar.
Output for the above code will be:
Iterating over a dictionary Iterating using a key alone in for loop key: firstName , value: john key: studentId , value: 415312 key: lastName , value: Smith key: age , value: 29 Iterating using key and value key: firstName , value: john key: studentId , value: 415312 key: lastName , value: Smith key: age , value: 29 ...Reached the end...
Iterating Over Sequence Using Index and Range
This is similar to the for loops that we see in languages like C/C++/Java etc. Elements of a given sequence are accessed using index.
The range() function is used to return a range of values starting from zero as lower bound to the value mentioned as a parameter in the upper bound. It is possible to get a sub-range by mentioning a lower bound and upper bound.
For example, range(2,6) returns 2, 3, 4, 5 whereas range(3) will return 0, 1, 2. In the following code, we use range(len(rhymes)) to direct python to iterate over positions 0, 1, 2, till the rhymes[length – 1] and print the values.
The output for the above code will be:
Recommended for you
Printing each word in new line accessed by index. Mary Had A Little Lamb
The While Loop
The general syntax of while loop can be represented as follows:
It repeatedly executes the steps as long as the condition holds true. So, an infinite loop can be easily written using this while loop just like how we create it in C/C++/Java using:
In the following program, we print numbers from 11 to 20 using a simple while loop.
The output of the above program will be as follows:
Counting from 11 to 20 11 12 13 14 15 16 17 18 19 20
It is possible to nest a loop within another loop. Consider the following sample program. It is designed to print a number pyramid in the following manner:
1 1 2 1 2 3 … 1 2 3 … n
In the first for loop, we specify the range’s lower limit as 1 and upper limit as 5+1. In the second loop, we specify the range from 1 to i+1 for each line. Note that the print statement has a parameter named end=” “.
This is to direct the interpreter to print further outputs in the same line and all these outputs shall be separated using the special character shown. If the statement is changed to print (j, end=", "), all numbers will have a trailing comma. Output for the above program will be:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Loop Control Statements
Python offers three control statements:
- Break statement: It terminates the loop statement and transfers the control outside the scope to the next statement following the loop.
- Continue statement: It causes the loop to skip the remaining steps of the loop but continue with the next iteration.
- Pass statement: It is often useful for debugging the code. Nothing really happens when the statement is executed.
Let us learn more about these statements with an example:
The output of the above code will be as follows:
Printing letters in Welcome till letter l W, e, Printing letters in welcome after omitting l W, e, c, o, m, e, Adding pass block when l is encountered W, e, Encountered pass block Continue printing l, c, o, m, e,
© 2019 Sam Shepards