Educational illustration showing Python loop syntax including for, while, range, break, and continue statements with code snippet and title ‘Mastering Python Loops’ for a programming tutorial blog.

Mastering Python Loops: For, While, Range, Break, Continue & More

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:

  1. For Loop – used to iterate over sequences like lists, tuples, strings, or ranges.
  2. 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:

  • num takes each value in nums one by one.
  • for loops 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:

  • while loops are used when you don’t know the number of iterations in advance.
  • Loop stops when the condition (i <= 5) becomes False.

Difference Between for and while Loops

FeatureFor LoopWhile Loop
IterationIterates over a sequence (list, tuple, string, range)Iterates until a condition is False
Use caseWhen the number of iterations is knownWhen iterations depend on dynamic conditions
IncrementAutomatic if using range()Must be manually done in the loop
RiskLess risk of infinite loopHigher 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-1
  • range(start, stop) → start to stop-1
  • range(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

KeywordEffect
breakExits the loop completely
continueSkips 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 break occurs, the else block 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 stops the loop completely.
  • continue skips the current iteration and moves to the next.
Q3: Explain pass in Python.
  • pass does nothing; used as a placeholder to avoid syntax errors.
Q4: Can loops have an else block?
  • Yes, else executes only if the loop finishes normally without a break.
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 !


Comments

Leave a Reply

Discover more from Learn With Nishtha

Subscribe now to keep reading and get access to the full archive.

Continue reading