Different types of loops in python
Loops are very important programming concepts used in most programming languages nowadays.
Loop is used to execute blocks of code multiple times. Concepts of the loop through elements are the same in all programming languages and only differ in loop syntax.
In this article we are going to learn Different types of loops in python with an example program.
So let’s begin…
There is basically two loop control statements in python in python used to iterate over sequence
- For loop
- While loop
There are different shades of for and while loops based on our requirements. We will go through various types of loop implementation and understand each step by step.
For loop is widely used to traverse a sequence list, a tuple, a dictionary, and a string.
For loop in python syntax
for iterator_index in sequence: Code statements to be executed
For loop in python example code
Print all name in list with length
names = ['Peter', 'Camren', 'Jo', 'Geoff', 'Andres'] for name in names: print(name, len(name))
Explanation: List of names is traversing until the list is done using a for loop. Variable name is representing each value from the list through. Therefore For the first iteration it will print name as Peter and length as 5 and so on.
Here is the output for above program
('Peter', 5) ('Camren', 6) ('Jo', 2) ('Geoff', 5) ('Andres', 6)
While loop is used to execute blocks of code until the condition is true.
while loop syntax in python
While conditionToCheck: Statements(block of code)
While loop in python example
count = 0 while (count < 5): count = count + 1 print("Hello there: ", count)
Explanation : Here the while loop will continue to execute its body until it meets condition count < 5 as true. For each iteration it increases count by 1 ( count = count + 1) and print "Hello there" & count value for each iteration.
('Hello there: ', 1) ('Hello there: ', 2) ('Hello there: ', 3) ('Hello there: ', 4) ('Hello there: ', 5)
We have already learned the basics about for & while loop with simple examples. Now we are going to see multiple scenarios related to loops such as The Infinite Loop,nested while loop in python, use of break and continue statements within loop and more with easy to understand example programs.
1. What is an infinite loop in python?
Infinite loop in python is a never ending process. It keeps executing it’s code block again and again.
Why? Because the condition used to check never becomes FALSE.
Let’s understand with below infinite loop example
Rewritten above while example code as
count = 0 while (count < 5): print("Hello there: ")
Explanation: Here condition count < 5 will always be TRUE because we miss to use Increment statement count = count + 1 here which results in an infinite loop and keeps print Hello there.
We are required to use CTRL+C to exit the infinite loop program.
2. Nested for loop in python with example
For Loop (Inner loop) inside another for loop (Outer loop) is called nested for loop. There can be multiple inner for loops that can be used as per scenario. Python supports nested inner loops.
Here is the question, Why do we need nested loops? Nested loops are mostly used for multidimensional data structures.
Let’s understand with the following nested for loop example.
employee = ["John", "Peter", "Jo"] books = ["Math", "Science", "English"] for x in employee: #Outer Loop for y in books: #Inner Loop print(x, y)
('John', 'Math') ('John', 'Science') ('John', 'English') ('Peter', 'Math') ('Peter', 'Science') ('Peter', 'English') ('Jo', 'Math') ('Jo', 'Science') ('Jo', 'English')
Explanation: Here we have two loops. Outer loop will iterate through a list of strings named as employees whereas Inner loop (Nested loop) will iterate through a list of strings named as books. Inner loops will start and complete all its iteration for each Outer loop iteration.
3. Nested while loop in python with example
While Loop (Inner loop) inside another while loop (Outer loop) is called nested while loop.
Let’s understand with the following nested while loop example.
i=1 while i<=3 : j=1 while j<=3: print(i, j) j+=1 i+=1;
Output: (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)
4. Looping Through a String using for loop
Iterating over the character of the string using a for loop is one the operations performed on strings in python.
for x in "QuizCure": print(x)
Q u i z C u r e
5. For Loop With Two Variables in Python
For a looping through a multi dimensional array or matrix we just need to use a nested loop using outer loop and inner loop where both loops have their own single variable defined.
There are ways to iterate for a loop with multiple parameters. It depends on the scenario such as traversing through multiple lists simultaneously, loop through dictionary elements and more.
Let’s see below example code for two list looping together with two params.
import itertools students = ["John", "Alex", "Jo"] books = ["Math", "Science"] for s,b in zip(students, books): print(s, b)
('John', 'Math') ('Alex', 'Science')