Python loops are control flow structures that allow us to execute a block of code repeatedly. Python provides two main types of loops – for and while. Additionally, there is support for nested loops in Python, allowing us to loop within loops to perform more complex tasks.

While all these loops offer similar basic functionality, they differ in their syntax and condition-checking time.
For Loop in Python
In Python, we use for loops for sequential traversal. For example, traversing the elements of a string, list, tuple, etc. It is the most commonly used loop in Python that allow us to iterate over a sequence when we know the number of iterations beforehand.

Syntax:
The following is the syntax of Python for Loop:
for element in given_sequence:
# some block of code
Simple Python for Loop Example
Let us take a look at a basic implementation of the for loop in Python:
Example
# example of a for loop in Python
# iterating using for loop
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Explanation:
Here, we have used a for loop to iterate through the numbers ranging from 1 to 5. In each iteration, the current number is stored and printed.
Iterating over a Sequence using Python for Loop
We can use for loop to iterate over strings, lists, tuples, and dictionaries in Python, as shown in the following example:
Example
# python example to show use of for loop in sequential traversal
# given string
str_1 = "Learn Python"
# iterating over string using for loop
for i in str_1:
print(i)
print()
# given list
list_1 = ["Welcome", "to", "Learn", "Python"]
# iterating over list using for loop
for i in list_1:
print(i)
print()
# given tuple
tuple_1 = ("Python", "for", "Beginners")
# iterating over tuple using for loop
for i in tuple_1:
print(i)
print()
# given dictionary
dict_1 = {
1: "Learn",
2: "Python"
}
# iterating over dictionary using for loop
for i in dict_1:
print(i, ":", dict_1[i])
Output:
L
e
a
r
n
P
y
T
h
o
n
Welcome
to
Learn
Python
Python
for
Beginners
1 : Learn
2 : Python
Explanation:
In this example, we have used the for loop to traverse different types of sequences such as string, list, tuple, and dictionary.
Iterating by the Index of Sequence
In Python, we can also use the index of the elements in the given sequence for iteration. The basic idea for this approach is first to determine the size of the sequence (e.g., list, tuple) and then iterate over it within the range of the determined length.
Let us take a look at the following example:
Example
# python example to iterate over sequence using index
# given list
fruit_basket = ['apple', 'banana', 'orange', 'mango', 'kiwi']
# iterating over the index of elements in the list
for i in range(len(fruit_basket)):
# printing the index and the item
print(i, ":", fruit_basket[i])
Output:
0 : apple
1 : banana
2 : orange
3 : mango
4 : kiwi
Explanation:
Here, we have used the len() function to determine the length of the given sequence and then used the range() function to generate the index values ranging from 0 to the length of the list minus 1. The for loop then prints both the index and the corresponding element.
Use of else Statement with Python For Loop
In Python, we can also use the else statement with the for loop. The for loop does not consist of any condition on the basis of which the execution will stop. Thus, the code inside the else block will only run once the for loop finishes iterations.
Syntax:
The syntax of the else statement with Python for loop is shown below:
for element in given_sequence:
# some block of code
else:
# some block of code runs if loop ends without break
Python for Loop Example using else Statement
Let us see an example of showing how the else statement works with the for loop in Python.
Example
# python example to show use of else statement with for loop
# given list
fruits = ['guava', 'apple', 'orange', 'mango', 'banana', 'melon']
# iterating with for loop
for item in fruits:
# inside for block
print(item) # printing items
else:
# inside else block
print("Welcome to else Block.") # printing statement
Output:
guava
apple
orange
mango
banana
melon
Welcome to else Block.
Explanation:
In this example, we have combined the else statement with the for loop. Since the for loop does not have any conditions, it iterated over the entire list and then executed the else block.
While Loop in Python
A while loop in Python allows us to execute a block of code repeatedly as long as a particular condition evaluates to True. It is usually utilized when the number of iterations is unknown beforehand.

Syntax:
It has the following syntax:
while given_condition:
# some block of code
Python While Loop Example
Let us now see a simple example of the while loop in Python.
Example
# example of a for loop in Python
# initializing a counter
counter = 1
# iterating using while loop
while counter <= 5:
print("Learn Python")
# incrementing counter by 1
counter += 1
Output:
Learn Python
Learn Python
Learn Python
Explanation:
In this example, we have used the while loop to print a statement five times. We have initialized a counter with an initial value of 1. We then define a condition in the while loop to iterate the loop as long as the counter is less than or equal to 5. Inside the loop statement, we have incremented the counter value by 1.
Use of else Statement with Python While Loop
Similar to the use of the else statement with the for loop, we can use it with Python while loop. The else block will run only when the loop condition becomes false, implying that the loop terminates normally.
Syntax:
The syntax of the else statement with Python for loop is shown below:
for element in given_sequence:
# some block of code
else:
# some block of code runs if loop ends without break
Python else statement Example with While Loop
We will now look at the following example to see the use of the else statement with the while loop in Python:
Example
# python example to show use of else statement with while loop
# given list
fruits = ['guava', 'apple', 'orange', 'mango', 'banana', 'melon']
# initializing a counter
counter = 0
# iterating with while loop
while counter < len(fruits):
# inside for block
print(fruits[counter])
# incrementing counter
counter += 1
else:
# inside else block
print("Welcome to else Block.") # printing statement
Output:
guava
apple
orange
mango
banana
melon
Welcome to else Block.
Explanation:
In this example, we have combined the else statement with the while loop. Since we have not used any break statement, the while loop runs until the given condition becomes false. After that, it will execute the print statement from the else block.
Infinite While Loop in Python
In Python, we can also create a loop to execute a block of code for infinite times using the while loop, as shown in the following example:
Example
# python example on infinite while loop
# initializing counter
counter = 0
# iterating using while loop
while counter == 0:
print("Learn Python")
# no increment statement
Output:
Learn Python
Learn Python
Learn Python
Learn Python
Learn Python
...
Explanation:
In this example, we have created an infinite while loop. Since the counter is initialized with the value of 0 and the condition counter == 0 always remains true, the loop runs forever, continuously printing the statement.
Note: It is suggested not to use this type of loop. It is a never-ending loop where the condition always remains true and we have to terminate the interpreter forcefully.
Nested Loops in Python
A nested loop is a loop inside another loop. In Python, we can nest both for and while loops. Nested loops are useful while working with multi-dimensional data like grids or matrices or while performing certain complex operations.
Syntax:
The following is the syntax of the Python nested for loop:
for outer_var in outer_sequence:
# some block of code in outer loop
for inner_var in inner_sequence:
# some block of code in inner loop
The syntax of the Python nested while loop is given below:
while outer_condition:
# some block of code in outer loop
while inner_condition:
# some block of code in inner loop
We can also use one type of loop inside another other type of loop in Python. For example, we can use a while loop inside a for loop or vice versa.
Python Nested Loop Example
Let us see an example of a Python nested loop.
Example
# python example to print a pattern using nested loop
# iterating using for loop
for i in range(1, 11):
# iterating using nested for loop
for j in range(1, i + 1):
# printing pattern
print("*", end=" ")
# new line
print()
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Explanation:
In this example, we use a nested for loop to print “*” multiple times in each row, where the number of times it prints increases with each iteration of the outer loop (based on the value of i).
Loop Control Statements in Python
In Python, we use loop control statements in order to change the sequence of execution. Once the execution leaves a scope, the objects created in the same scope are also destroyed automatically.
Python offers support for the following control statements:
| Loop Control Statement | Description |
|---|---|
| Continue | It returns the control to the beginning of the loop |
| Break | It terminates the loop immediately, even if the condition or sequence is not finished. |
| Pass | It acts as a placeholder that does nothing. |
Let us take a look at the following example demonstrating the use of these control statements in Python.
Example
# python example to show the use of different loop control statements
print("Example with continue statement:")
for i in range(1, 6):
if i == 3:
# continue statement
continue # Skip the iteration when i is 3
print(i)
print("\nExample with break statement:")
for i in range(1, 6):
if i == 4:
# break statement
break # Exit the loop when i is 4
print(i)
print("\nExample with pass statement:")
for i in range(1, 4):
if i == 2:
# pass statement
pass # Do nothing when i is 2
else:
print(i)
Output:
Example with continue statement:
1
2
4
5
Example with break statement:
1
2
3
Example with pass statement:
1
3
Explanation:
In this example, we have used the different loop control statements. The continue statement is used to skip the iteration when i = 3, so 3 is not printed. The break statement is used to terminate the loop when i = 4. The pass statement here did nothing and simply acted as a placeholder.
Conclusion
In this tutorial, we learned about loops in Python. We understand how loops act as an essential part of programming to automate repetitive tasks and to iterate over sequences like strings, lists, or ranges. Python provides mainly two types of loops – for and while, along with control statements like continue, break, and pass that help us to write flexible and efficient code.
Leave a Reply