Loops in Python
Loops in Python allow executing a block of code multiple times, making programs more efficient. Python provides two types of loops:
for
Loop – Used when iterating over sequences like lists, tuples, or strings.while
Loop – Used when the number of iterations is not known beforehand, and execution depends on a condition.
Additionally, Python offers loop control statements (break
, continue
, pass
) to modify loop behavior.
1. for
Loop
A for
loop iterates over a sequence (list, tuple, dictionary, string, or range).
Syntax:
for variable in sequence:
# Code to execute
Example 1: Printing Numbers from 0 to 10
for x in range(11):
print(x)
Output:
0
1
2
3
4
5
6
7
8
9
10
Example 2: Iterating Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 3: Printing Odd Numbers from 0 to 20
for x in range(21):
if x % 2 != 0:
print(x)
Output:
1
3
5
7
9
11
13
15
17
19
Example 4: Reverse Loop (Descending Order)
for x in range(10, 0, -1):
print(x)
Output:
10
9
8
7
6
5
4
3
2
1
2. while
Loop
A while
loop runs until a specified condition is False
. It is useful when the number of iterations is unknown.
Syntax:
while condition:
# Code to execute
Example 1: Printing Numbers from 1 to 10
x = 1
while x <= 10:
print(x)
x += 1
Output:
1
2
3
4
5
6
7
8
9
10
Example 2: Sum of First n
Natural Numbers
n = int(input("Enter a number: "))
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print("Sum of first", n, "numbers is:", sum)
If the user enters 5
, the output will be:
Sum of first 5 numbers is: 15
3. Loop Control Statements
Loop control statements alter the normal flow of loops. Python provides three main control statements:
3.1 break
Statement (Exits the Loop)
The break
statement stops the loop immediately when a condition is met.
for i in range(10):
if i == 7:
print("Processing stopped at 7")
break
print(i)
Output:
0
1
2
3
4
5
6
Processing stopped at 7
3.2 continue
Statement (Skips Current Iteration)
The continue
statement skips the current iteration and moves to the next one.
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output:
1
3
5
7
9
3.3 pass
Statement (Does Nothing)
The pass
statement acts as a placeholder where code is required but no operation is needed.
for i in range(5):
if i == 3:
pass # Placeholder for future implementation
print(i)
Output:
0
1
2
3
4
4. Nested Loops
A loop inside another loop is called a nested loop.
Example: Printing a Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
5. else
in Loops
Python allows an else
block in loops, which executes only if the loop completes normally without break
.
Example: Checking a List of Items
cart = [10, 20, 30, 40, 50]
for item in cart:
if item >= 500:
print("Cannot process this order")
break
print(item)
else:
print("All items processed successfully!")
Output:
10
20
30
40
50
All items processed successfully!
6. Infinite Loops
An infinite loop runs indefinitely until manually stopped.
Example: Infinite Loop Using while True
i = 0
while True:
i += 1
print("Hello", i)
if i == 5:
break # Stops after 5 iterations
Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
7. Key Differences Between for
and while
Loops
Feature |
|
|
---|---|---|
Usage |
Used when the number of iterations is known |
Used when the number of iterations is unknown |
Condition |
Iterates over a sequence (list, string, range, etc.) |
Runs until a condition becomes |
Example |
|
|
8. Summary of Loop Control Statements
Control Statement |
Description |
Example |
---|---|---|
|
Exits the loop immediately |
|
|
Skips the current iteration |
|
|
Does nothing, acts as a placeholder |
|
Conclusion
- Python provides two types of loops:
for
(when the number of iterations is known) andwhile
(when the number of iterations is unknown). - Loop control statements (
break
,continue
,pass
) modify loop behavior. - Nested loops allow complex iterations.
else
in loops executes only if the loop completes normally.