Python loops are fundamental programming constructs that allow you to repeatedly execute a block of code as long as a specified condition is true or until a certain sequence is completed. Python supports two main types of loops: for
loops and while
loops. Let’s explore each in detail.
1. For Loop
The for
loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in that sequence.
Syntax of For Loop
for item in sequence:
# Block of code to be executed
item
: Represents the current element in the sequence.sequence
: Represents the collection of items being iterated over (e.g., list, tuple, string, range).
Example of For Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Range in For Loop
The range()
function is commonly used with for
loops to generate a sequence of numbers.
for i in range(5):
print(i)
Output:0
1
2
3
4
range(5)
generates numbers from 0 to 4.
Loop with Else Clause
Python allows you to use an else
clause with loops. The else
block is executed when the loop completes its iteration over the sequence without being interrupted by a break
.
for i in range(3):
print(i)
else:
print("Loop completed")
Output:0
1
2
Loop completed
2. While Loop
The while
loop in Python repeatedly executes a block of code as long as a specified condition remains true.
Syntax of While Loop
while condition:
# Block of code to be executed
condition
: A Boolean expression that is evaluated before each iteration. IfTrue
, the loop continues; ifFalse
, the loop stops.
Example of While Loop
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Infinite Loop
A while
loop can become an infinite loop if the condition never becomes False
. This should be avoided unless intentionally required (e.g., in servers or event listeners).
# Example of an infinite loop (this loop will run forever)
while True:
print("This will continue forever")
3. Control Statements in Loops
Python provides several control statements to manage the flow of loops:
a. Break Statement
The break
statement is used to exit a loop prematurely, regardless of the loop’s condition.
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
b. Continue Statement
The continue
statement skips the current iteration and proceeds with the next iteration of the loop.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
- The number
2
is skipped in the output.
c. Pass Statement
The pass
statement does nothing. It is a placeholder used when a statement is syntactically required but no action is needed.
for i in range(5):
if i == 2:
pass # Do nothing
print(i)
Output:
0
1
2
3
4
4. Nested Loops
Python allows you to use loops within loops, known as nested loops. Each loop can be of any type (for
or while
), and they can be mixed.
Example of Nested Loops
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
Output:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
5. Loop with Else Clause
As mentioned earlier, you can use an else
clause with both for
and while
loops. The else
block is executed when the loop is exhausted (i.e., when the loop condition becomes False
or the sequence is fully iterated).
Example with For Loop
for i in range(5):
print(i)
else:
print("Loop completed successfully")
Output:
0
1
2
3
4
Loop completed successfully
Example with While Loop
i = 0
while i < 3:
print(i)
i += 1
else:
print("Loop ended with i =", i)
Output:
0
1
2
Loop ended with i = 3
6. Practical Examples of Loops
a. Sum of First N Natural Numbers
n = 5
sum_n = 0
for i in range(1, n + 1):
sum_n += i
print(f"Sum of first {n} natural numbers is {sum_n}")
Output:
sql
Sum of first 5 natural numbers is 15
b. Multiplication Table
number = 3
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
Output:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
...
3 x 10 = 30
7. Key Points to Remember
- For Loop: Best used for iterating over a sequence when the number of iterations is known.
- While Loop: Best used when the number of iterations is not known beforehand and depends on a condition.
- Control Statements:
break
,continue
, andpass
allow you to control the flow of loops effectively. - Nested Loops: Useful when dealing with multi-dimensional data or when multiple levels of iteration are needed.
Loops are powerful constructs in Python, enabling repetitive tasks to be performed efficiently. Understanding how to use loops effectively is crucial for writing clear, concise, and efficient Python code.