In Python, loops serve as control flow mechanisms that enable the repeated execution of a specific block of code. The language offers two primary varieties of loops: for and while. Furthermore, Python supports the implementation of nested loops, which allows for looping within other loops to tackle more intricate tasks.
Although all these looping constructs provide comparable fundamental capabilities, they vary in their syntax and the timing of their condition evaluations.
For Loop in Python
In Python, the for loop is utilized for sequential iteration. For instance, it can be employed to navigate through the components of a string, list, tuple, and more. This loop is the most frequently utilized type in Python, enabling us to loop through a sequence when the total number of iterations is predetermined.
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 examine a fundamental example of how the for loop operates 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:
In this example, a for loop has been employed to traverse the integers from 1 to 5. During each iteration, the current integer is assigned to a variable and subsequently displayed.
Iterating over a Sequence using Python for Loop
In Python, a for loop can be utilized to traverse through strings, lists, tuples, and dictionaries. This is illustrated in the example below:
Example
# python example to show use of for loop in sequential traversal
# given string
str_1 = "Example"
# iterating over string using for loop
for i in str_1:
print(i)
print()
# given list
list_1 = ["Welcome", "to", "Example", "Tech"]
# 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: "Example",
2: "Tech"
}
# iterating over dictionary using for loop
for i in dict_1:
print(i, ":", dict_1[i])
Output:
T
p
o
i
n
t
T
e
c
h
Welcome
to
Example
Tech
Python
for
Beginners
1 : C# Tutorial
2 : Tech
Explanation:
In this illustration, we have employed the for loop to iterate over various kinds of sequences, including strings, lists, tuples, and dictionaries.
Iterating by the Index of Sequence
In Python, it is also possible to iterate through a sequence by utilizing the indices of its elements. The fundamental concept behind this method involves first calculating the total number of elements in the sequence (such as a list or tuple) and subsequently looping through it using a range that corresponds to the calculated 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:
In this instance, we employed the len function to ascertain the length of the specified sequence. Subsequently, we utilized the range function to create index values that span from 0 to the length of the list, subtracting 1. The for loop then outputs both the index and its associated element.
Use of else Statement with Python For Loop
In Python, it is also possible to incorporate the else statement within a for loop. Unlike traditional loops that rely on a condition to determine when to terminate, the for loop executes its code block until it has completed all iterations. Therefore, the code contained within the else block will execute only after the for loop has finished processing all its iterations.
Syntax:
The structure of the else statement when utilized with a for loop in Python is illustrated 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's examine an example that demonstrates the functionality of the else statement in conjunction 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 illustration, we have integrated the else clause with the for loop. Given that the for loop does not include any conditional statements, it traversed the complete list and subsequently executed the else section.
While Loop in Python
A while loop in Python enables the repeated execution of a code block as long as a specified condition remains True. This construct is typically employed in scenarios where the total number of iterations cannot be predetermined.
Syntax:
It has the following syntax:
while given_condition:
# some block of code
Python While Loop Example
Now, let's examine a straightforward illustration 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("Example")
# incrementing counter by 1
counter += 1
Output:
Example
Example
Example
Example
Example
Explanation:
In this illustration, we employed a while loop to output a statement five times. We began by setting a counter to an initial value of 1. Subsequently, we established a condition within the while loop that allows the loop to continue executing as long as the counter remains less than or equal to 5. Within the body of the loop, we increment the counter by 1 with each iteration.
Use of else Statement with Python While Loop
In a manner akin to utilizing the else statement with a for loop, it is also applicable with the while loop in Python. The else segment will execute exclusively when the condition of the loop evaluates to false, indicating that the loop has concluded in a standard manner.
Syntax:
The structure of the else statement in conjunction with a for loop in Python is illustrated as follows:
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
Next, we will examine the example below to illustrate how the else statement operates in conjunction 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 instance, we have integrated the else clause with the while loop. Given that we have not employed any break statement, the while loop will continue to execute as long as the specified condition remains true. Once that condition evaluates to false, the print statement contained within the else block will be executed.
Infinite While Loop in Python
In Python, it is also possible to establish a loop that repeatedly executes a section of code indefinitely by utilizing the while loop, illustrated in the example below:
Example
# python example on infinite while loop
# initializing counter
counter = 0
# iterating using while loop
while counter == 0:
print("Example")
# no increment statement
Output:
Example
Example
Example
Example
Example
...
Explanation:
In this illustration, an infinite while loop has been established. The counter begins at a value of 0, and because the condition counter == 0 persistently evaluates to true, the loop executes indefinitely, repeatedly outputting 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 refers to a loop that exists within another loop. In Python, it is possible to nest both for loops and while loops. The use of nested loops is particularly beneficial when dealing with multi-dimensional datasets such as grids or matrices, or when executing specific intricate operations.
Syntax:
The syntax for a nested for loop in Python is as follows:
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 structure of a nested while loop in Python is outlined as follows:
while outer_condition:
# some block of code in outer loop
while inner_condition:
# some block of code in inner loop
In Python, it is also possible to nest one type of loop within another. For instance, you can place a while loop inside a for loop, or you can do the opposite by incorporating a for loop within a while loop.
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 illustration, we implement a nested for loop to display the character "*" repeatedly on each row. The frequency of its appearance escalates with each cycle of the outer loop, which is determined by the current value of i.
Loop Control Statements in Python
In Python, loop control statements are utilized to modify the order of execution. When the execution exits a particular scope, any objects that were instantiated within that scope are automatically disposed of.
Python provides functionality for the subsequent 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 illustration, various loop control statements have been implemented. The continue statement is utilized to bypass the current iteration when i = 3, resulting in the omission of the value 3 from being printed. The break statement is employed to halt the loop execution when i reaches 4. Meanwhile, the pass statement serves no operational purpose here and functions merely as a placeholder.
Conclusion
In this guide, we explored the concept of loops in Python. We recognize that loops serve as a fundamental component in programming, allowing for the automation of repetitive tasks and the iteration over sequences such as strings, lists, or ranges. Python primarily offers two categories of loops: for and while. Additionally, it includes control statements such as continue, break, and pass, which assist in crafting code that is both versatile and efficient.
Python Loops MCQs
- Which of the following is used to repeat a block of code in Python?
- If statement
- Loop
- Function
- Class
Response: b) Loop
- What will be the result of executing the code below?
for i in range(1, 4):
print(i)
- 0 1 2
- 0 1 2 3
- 1 2 3
- 1 2 3 4
- What does the break statement do in a loop?
- Skips the current iteration
- Does nothing
- Repeats the loop again
- Exits the loop completely
- Which loop is best used when the number of iterations is unknown?
- for loop
- while loop
- do-while loop
- switch loop
Response: b) while loop
- What will be the result when executing the following code?
for i in range(5):
if i == 2:
continue
print(i)
- 0 1 3 4
- 0 1 2 3 4
- 1 2 3 4
- 0 1 2