Python Loops
Introduction
Loops are one of the most important concepts in Python programming. They allow us to execute a block of code repeatedly without writing the same statements multiple times.
For example, if we want to print numbers from 1 to 100, writing 100 separate print statements would be inefficient. Instead, we can use a loop.
Python provides two main types of loops:
whileloopforloop
Python also supports nested loops and loop control statements such as break, continue, and pass.
In this article, we will understand all these concepts with practical examples and programming exercises.
1. Need for Loops in Python
Loops help us perform repetitive tasks efficiently.
Consider this example without a loop:
print(1)
print(2)
print(3)
print(4)
print(5)
We can write the same program using a loop:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Using loops makes programs shorter, easier to understand, and easier to maintain.
2. While Loop in Python
A while loop executes a block of code repeatedly as long as the given condition is True.
It is useful when the number of iterations is not known in advance.
Syntax
while condition:
# Statements to execute
Example 1: Print Numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Explanation:
- Initially,
i = 1. - Python checks whether
i <= 5. - If the condition is True, it prints the value of
i. - The value of
iincreases by 1. - When
ibecomes 6, the condition becomes False and the loop stops.
Example 2: Multiplication Table Using While Loop
number = int(input("Enter the number: "))
i = 1
while i < 11:
print(number, "*", i, "=", number * i)
i += 1
Sample Input:
Enter the number: 5
Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Example 3: Sum of Digits of a Number
This program calculates the sum of all digits in a number.
number = int(input("Enter a number: "))
total = 0
while number > 0:
digit = number % 10
total += digit
number = number // 10
print("Sum of digits:", total)
Sample Input:
Enter a number: 345
Output:
Sum of digits: 12
Explanation:
345 % 10gives 5.345 // 10gives 34.34 % 10gives 4.34 // 10gives 3.- The final digit is 3.
- The sum is 5 + 4 + 3 = 12.
Example 4: Accept Numbers Until the User Enters 0 and Calculate Average
In this program, the user can enter multiple numbers. The loop stops when the user enters 0.
total = 0
count = 0
while True:
number = int(input("Enter a number (0 to stop): "))
if number == 0:
break
total += number
count += 1
if count > 0:
average = total / count
print("Average:", average)
else:
print("No numbers entered")
Sample Input:
Enter a number (0 to stop): 10
Enter a number (0 to stop): 20
Enter a number (0 to stop): 30
Enter a number (0 to stop): 0
Output:
Average: 20.0
3. While Loop with Else
Python allows an else block with a while loop.
The else block executes when the loop terminates normally because its condition becomes False.
Example
x = 1
while x < 3:
print(x)
x += 1
else:
print("Limit crossed")
Output:
1
2
Limit crossed
Important: The loop’s else block does not execute if the loop is terminated using break.
4. Number Guessing Game Using While Loop
A number guessing game is a practical application of loops.
In this program, Python generates a random number between 1 and 100. The user must guess the correct number.
import random
jackpot = random.randint(1, 100)
guess = int(input("Guess the number: "))
counter = 1
while guess != jackpot:
if guess < jackpot:
print("Wrong! Guess higher")
else:
print("Wrong! Guess lower")
guess = int(input("Guess again: "))
counter += 1
else:
print("Correct guess!")
print("Attempts:", counter)
Possible Output:
Guess the number: 40
Wrong! Guess higher
Guess again: 70
Wrong! Guess lower
Guess again: 55
Correct guess!
Attempts: 3
The actual output depends on the randomly generated number and the user’s guesses.
5. For Loop in Python
A for loop is used to iterate over the items of a sequence or iterable, such as a list, tuple, string, set, or range.
It is useful when we want to process each item in a collection.
Syntax
for variable in sequence:
# Statements to execute
Example 1: Iterate Through a Set
for i in {1, 2, 3, 4, 5}:
print(i)
Output:
1
2
3
4
5
Note: Sets are unordered collections, so their iteration order is not guaranteed.
Example 2: Iterate Through a List
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
Output:
Apple
Banana
Mango
Example 3: Iterate Through a String
name = "Python"
for character in name:
print(character)
Output:
P
y
t
h
o
n
6. Range Function in Python
The range() function generates a sequence of integers. It is commonly used with for loops.
Syntax
range(start, stop, step)
start: Starting value; defaults to 0.stop: Ending limit; this value is excluded.step: Difference between consecutive values; defaults to 1.
Example 1: Using range()
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Example 2: Using range() with Step
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
Example 3: Reverse Iteration
for i in range(5, 0, -1):
print(i)
Output:
5
4
3
2
1
7. Practical Problem: Population Calculation
Problem:
The current population of a town is 10,000. The population increases by 10% every year. Write a program to calculate the population at the end of each of the previous ten years.
Program
curr_pop = 10000
for i in range(10, 0, -1):
print(i, curr_pop)
curr_pop /= 1.1
Output (rounded):
10 10000
9 9090.91
8 8264.46
7 7513.15
6 6830.13
5 6209.21
4 5644.74
3 5131.58
2 4665.07
1 4240.98
Explanation:
If the population increases by 10%, the next year’s population is:
Current Population = Previous Population × 1.1
To calculate the previous year’s population:
Previous Population = Current Population / 1.1
The loop repeats this calculation ten times.
8. Sequence Sum Using For Loop
Consider the following mathematical series:
[
\frac{1}{1!}+\frac{2}{2!}+\frac{3}{3!}+\cdots+\frac{n}{n!}
]
We can calculate the sum using a for loop.
Program
n = int(input("Enter the number of terms: "))
fact = 1
total = 0
for i in range(1, n + 1):
fact *= i
total += i / fact
print("Sum:", total)
Sample Input:
Enter the number of terms: 3
Output:
Sum: 2.5
Explanation:
For three terms:
[
\frac{1}{1!}+\frac{2}{2!}+\frac{3}{3!}
=1+1+0.5=2.5
]
9. Difference Between For Loop and While Loop
| For Loop | While Loop |
|---|---|
| Iterates over a sequence or iterable | Repeats while a condition is True |
| Commonly used for collections and ranges | Commonly used when repetition depends on a condition |
| Automatically gets the next item from the iterable | Usually requires updating variables used in the condition |
Example: for i in range(5) | Example: while i < 5 |
When to use a for loop:
- To iterate over a list or tuple.
- To process every character in a string.
- To execute a known range of iterations.
When to use a while loop:
- When repetition depends on a condition.
- When the number of iterations is unknown.
- When a program should continue until a user enters a particular value.
10. Nested Loops in Python
A nested loop means placing one loop inside another loop.
The inner loop executes completely for every iteration of the outer loop.
Syntax
for i in range(outer_range):
for j in range(inner_range):
# Statements
Example 1: Basic Nested For Loop
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Explanation:
- The outer loop runs three times.
- For every outer iteration, the inner loop runs three times.
- Total executions of the inner statement = 3 × 3 = 9.
Example 2: Unique Combinations of 1, 2, 3 and 4
The following program generates combinations of three different digits using the numbers 1, 2, 3 and 4.
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if i != j and j != k and i != k:
print(i, j, k)
Possible Output:
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
...
4 3 2
The condition ensures that all three digits are different.
Example 3: Pattern Printing Using Nested Loops
Nested loops are commonly used to print patterns in Python.
Pattern 1:
***
****
***
Program:
for i in range(1, 4):
if i == 2:
print("*" * 4)
else:
print("*" * 3)
Output:
***
****
***
Pattern 2:
1
121
12321
1234321
Program:
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end="")
for j in range(i - 1, 0, -1):
print(j, end="")
print()
Output:
1
121
12321
1234321
11. Loop Control Statements in Python
Loop control statements change the normal execution of a loop.
Python provides three important loop control statements:
breakcontinuepass
A. Break Statement
The break statement immediately terminates the nearest enclosing loop.
It is useful when we want to stop a loop after a particular condition is satisfied.
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
When i becomes 5, the loop terminates.
Practical Example: Linear Search
Linear search checks each element of a list until the required element is found.
numbers = [10, 20, 30, 40, 50]
target = 30
found = False
for number in numbers:
if number == target:
found = True
break
if found:
print("Element found")
else:
print("Element not found")
Output:
Element found
The break statement stops the loop as soon as the target element is found.
Example: Find Prime Numbers in a Range
for num in range(2, 21):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)
Output:
2
3
5
7
11
13
17
19
The inner loop uses break when it finds a divisor, because the number cannot be prime.
B. Continue Statement
The continue statement skips the remaining statements in the current iteration and moves to the next iteration of the loop.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
When i becomes 3, Python skips the print statement for that iteration and continues with the next value.
Practical Example: Skip Out-of-Stock Products
products = [
{"name": "Laptop", "stock": 5},
{"name": "Mouse", "stock": 0},
{"name": "Keyboard", "stock": 3},
{"name": "Monitor", "stock": 0}
]
for product in products:
if product["stock"] == 0:
continue
print(product["name"], "is available")
Output:
Laptop is available
Keyboard is available
The program skips products whose stock is zero.
C. Pass Statement
The pass statement is a null operation. It does nothing when executed.
It is used as a placeholder when a statement is syntactically required but the implementation is not yet written.
Example:
for i in range(1, 6):
if i == 3:
pass
print(i)
Output:
1
2
3
4
5
Unlike continue, pass does not skip the current iteration. Execution continues with the next statement.
Difference Between Break, Continue and Pass
| Statement | Purpose |
|---|---|
break | Terminates the nearest enclosing loop |
continue | Skips the rest of the current iteration |
pass | Does nothing; acts as a placeholder |
12. Common Mistakes in Python Loops
Mistake 1: Forgetting to Update the While Loop Variable
Incorrect code:
i = 1
while i <= 5:
print(i)
This creates an infinite loop because i never changes.
Correct code:
i = 1
while i <= 5:
print(i)
i += 1
Mistake 2: Forgetting That range() Excludes the Stop Value
for i in range(1, 5):
print(i)
Output:
1
2
3
4
The value 5 is not included.
Mistake 3: Incorrect Indentation
Python uses indentation to identify the statements belonging to a loop.
Incorrect indentation can cause an IndentationError or change the program’s behaviour.
Mistake 4: Using break Outside a Loop
The break statement can only be used inside a loop. Using it outside a loop causes a SyntaxError.
13. Summary of Python Loops
| Concept | Description |
|---|---|
while loop | Repeats while a condition is True |
for loop | Iterates over an iterable |
range() | Generates a sequence of integers |
| Nested loops | A loop inside another loop |
while-else | Executes else after normal loop completion |
break | Terminates the nearest enclosing loop |
continue | Skips the current iteration |
pass | Does nothing; used as a placeholder |
14. Practice Questions (MCQs)
Q1. Which loop executes as long as a condition is True?
A. for
B. while
C. if
D. else
Correct Answer: B. while
Q2. What is the output of the following code?
for i in range(1, 5):
print(i)
A. 1, 2, 3, 4, 5
B. 0, 1, 2, 3, 4
C. 1, 2, 3, 4
D. 2, 3, 4, 5
Correct Answer: C. 1, 2, 3, 4
Q3. Which function is commonly used to generate a sequence of numbers for a for loop?
A. input()
B. type()
C. range()
D. print()
Correct Answer: C. range()
Q4. What is the purpose of the break statement?
A. Skip the current iteration
B. Terminate the nearest enclosing loop
C. Restart the loop
D. Do nothing
Correct Answer: B. Terminate the nearest enclosing loop
Q5. Which statement skips the current iteration and continues with the next one?
A. break
B. pass
C. continue
D. return
Correct Answer: C. continue
Q6. What is the purpose of the pass statement?
A. Stop a loop
B. Skip an iteration
C. Do nothing and act as a placeholder
D. Restart a loop
Correct Answer: C. Do nothing and act as a placeholder
Q7. What is a nested loop?
A. A loop inside another loop
B. A loop inside a variable
C. A function inside a loop
D. A condition inside a variable
Correct Answer: A. A loop inside another loop
Q8. What is the output of the following code?
for i in range(1, 5):
if i == 3:
continue
print(i)
A. 1, 2, 3, 4
B. 1, 2, 4
C. 3, 4
D. 1, 2
Correct Answer: B. 1, 2, 4
Q9. When does the else block of a while loop execute?
A. Whenever break executes
B. When the loop terminates normally because its condition becomes False
C. Before the loop starts
D. After every iteration
Correct Answer: B. When the loop terminates normally because its condition becomes False
Q10. What happens if the variable in a while loop condition is never updated and the condition remains True?
A. The loop executes once
B. The loop creates an infinite loop
C. The loop automatically stops
D. Python ignores the loop
Correct Answer: B. The loop creates an infinite loop
Practice these programs regularly to improve your problem-solving and programming skills.