Estimated reading time: 3.5 mins read
Understanding Python Loops
Python loops are essential for automating repetitive tasks. Whether you’re summing numbers, iterating through lists, or processing user input, loops make your code efficient, readable, and scalable. This guide explains Python loops in detail with examples, beginner-friendly explanations, and advanced tips.
Python provides two main types of loops:
- For Loop – used to iterate over sequences like lists, tuples, strings, or ranges.
- While Loop – runs as long as a condition remains
True.
For Loop Example
# List of numbers
nums = [1, 2, 3, 4, 5]
# Loop through each number in the list
for num in nums:
print(f"Number is: {num}")
Explanation:
numtakes each value innumsone by one.forloops are best when you know the number of iterations or want to iterate through a collection.
While Loop Example
# Initialize variable
i = 1
# Loop continues as long as i <= 5
while i <= 5:
print(f"Value of i: {i}")
i += 1 # Increment i to avoid infinite loop
Explanation:
whileloops are used when you don’t know the number of iterations in advance.- Loop stops when the condition (
i <= 5) becomesFalse.
Difference Between for and while Loops
| Feature | For Loop | While Loop |
|---|---|---|
| Iteration | Iterates over a sequence (list, tuple, string, range) | Iterates until a condition is False |
| Use case | When the number of iterations is known | When iterations depend on dynamic conditions |
| Increment | Automatic if using range() | Must be manually done in the loop |
| Risk | Less risk of infinite loop | Higher risk of infinite loop if condition not handled |
Range Function
range() generates a sequence of numbers, which is commonly used with for loops.
# Numbers from 0 to 4
for i in range(5):
print(i)
# Numbers from 1 to 9
for i in range(1, 10):
print(i)
# Numbers from 1 to 5 skipping 1 each time
for i in range(1, 6, 2):
print(i)
Explanation:
range(stop)→ 0 to stop-1range(start, stop)→ start to stop-1range(start, stop, step)→ increments by step
Break and Continue
Break
Stops the loop immediately.
for i in range(1, 6):
if i == 3:
break # Stop the loop when i is 3
print(i)
Output:
1
2
Explanation: Loop stops when condition matches.
Continue
Skips the current iteration and continues with the next one.
for i in range(1, 6):
if i == 3:
continue # Skip printing 3
print(i)
Output:
1
2
4
5
Difference Between break and continue
| Keyword | Effect |
|---|---|
| break | Exits the loop completely |
| continue | Skips the current iteration and continues |
Pass Statement
pass does nothing but acts as a placeholder. Useful when the syntax requires a statement but you don’t want to write code yet.
for i in range(5):
pass # Placeholder, does nothing
print("End of program")
Explanation: Prevents syntax errors for empty loops, functions, or conditionals.
Else in Loops
Python allows else with loops. It executes only if the loop completes normally (not terminated by break).
For Loop Else Example
nums = [1, 2, 3]
for num in nums:
print(num)
else:
print("Loop finished without break")
While Loop Else Example
i = 1
while i <= 3:
print(i)
i += 1
else:
print("While loop finished normally")
Explanation:
- If a
breakoccurs, theelseblock is skipped. - Useful for searching algorithms when you want to know if a value wasn’t found.
Practical Examples
Sum of Numbers Using For Loop
n = int(input("Enter a number: "))
total = 0
for i in range(1, n + 1):
total += i
print(f"Sum of first {n} numbers is {total}")
Factorial Using While Loop
n = int(input("Enter a number: "))
fact = 1
i = 1
while i <= n:
fact *= i
i += 1
print(f"Factorial of {n} is {fact}")
Important Interview Qs&As
Q1: Difference between for and while loop?
- For loop iterates over sequences
- while loop runs until a condition becomes False.
Q2: What is break and continue?
break and continue?breakstops the loop completely.continueskips the current iteration and moves to the next.
Q3: Explain pass in Python.
pass in Python.passdoes nothing; used as a placeholder to avoid syntax errors.
Q4: Can loops have an else block?
else block?- Yes,
elseexecutes only if the loop finishes normally without abreak.
Q5: How do you generate a sequence of numbers in Python?
- Using
range(start, stop, step). Step is optional and defaults to 1.
Happy Learning !


Leave a Reply