Python Loops Explained: for Loop & while Loop with Examples (Beginner Guide)
π Loops in Python
Complete Guide
for Loop · while Loop · Nested · break · continue · pass · Real-Life Uses
A loop in Python is a programming structure that repeats a block of code multiple times. Instead of writing the same code again and again, you write it once inside a loop and Python executes it as many times as needed. Loops save time, reduce errors, and make programs much shorter and smarter.
For example, if you want to print numbers from 1 to 100, you do not need to write 100 print statements. You just write one loop and it does the job automatically.
print(1) print(2) print(3) # ... 100 lines needed!
for i in range(1, 101): print(i) # Just 2 lines — prints 1 to 100!
Python has two main types of loops — the for loop and the while loop. Each is used in different situations.
| Type | Used When | Example |
|---|---|---|
| for loop | You know the number of times | Loop 5 times |
| while loop | You repeat until condition is False | Loop until user quits |
A for loop is used to iterate (go through) each item in a sequence — such as a list, tuple, string, or range. It runs the code block once for every item in the sequence. The loop automatically stops when all items have been processed. You do not need to manually track or increment a counter — Python handles it for you. For loops are the most commonly used loops in Python.
i) takes each value from the sequence one by one on every iteration.
# range(stop) — 0 to stop-1 range(5) # 0,1,2,3,4 # range(start, stop) range(1, 6) # 1,2,3,4,5 # range(start, stop, step) range(0, 10, 2) # 0,2,4,6,8
range(5) gives 0,1,2,3,4 — not 5.
for i in range(1, 6): print(i)
2
3
4
5
fruits = ["apple", "banana", "mango"] for fruit in fruits: print(fruit)
banana
mango
for letter in "Python": print(letter)
y
t
h
o
n
total = 0 for i in range(1, 11): total += i print("Sum:", total)
A while loop repeats a block of code as long as a given condition is True. It keeps running until the condition becomes False. Unlike the for loop, the while loop does not automatically track iterations — you must manually update the variable inside the loop. While loops are best used when you do not know in advance how many times the loop should run, such as waiting for user input or processing until a task is complete.
i = 1 while i <= 5: print(i) i += 1 # ← very important!
2
3
4
5
i = 1 while i <= 3: print("Running:", i) i += 1 else: print("Loop finished!")
Running: 2
Running: 3
Loop finished!
n = 5 while n > 0: print(n) n -= 1 print("Go!")
4
3
2
1
Go!
total = 0 num = 1 while num <= 5: total += num num += 1 print("Total:", total)
password = "1234" attempt = "" tries = 0 while attempt != password: attempt = input("Enter password: ") tries += 1 print(f"Correct! Tries: {tries}")
| Feature | for Loop | while Loop |
|---|---|---|
| Based on | Sequence / range | Condition |
| Counter | Auto-managed | Manual update |
| Use when | Count is known | Count unknown |
| Risk | No infinite loop | Can run forever |
| Shorter? | Usually shorter | Can be longer |
| Example | Print 1 to 10 | Wait for input |
for i in range(1, 4): print(i) # 1 2 3
i = 1 while i <= 3: print(i) # 1 2 3 i += 1
Loop control statements change the normal flow of a loop. Python has three: break, continue, and pass.
| Statement | What it does |
|---|---|
| break | Stops the loop completely and exits |
| continue | Skips current iteration, goes to next |
| pass | Does nothing — placeholder |
for i in range(1, 6): if i == 3: break # stop loop print(i)
2
for i in range(1, 6): if i == 3: continue # skip 3 print(i)
2
4
5
for i in range(3): pass # does nothing, no error print("Done")
A nested loop is a loop written inside another loop. The outer loop runs once, and for each run of the outer loop, the inner loop runs completely. Nested loops are used for working with grids, tables, multiplication tables, patterns, and 2D data structures like matrices. The total number of iterations = outer loop count × inner loop count.
for i in range(1, 4): for j in range(1, 4): print(i, "x", j, "=", i*j)
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
for i in range(1, 5): print("* " * i)
* *
* * *
* * * *
Beginners often make these common mistakes when writing loops in Python. Knowing them helps you avoid errors early.
❌ Mistake 1 — Forgetting to update counter in while:i = 1 while i <= 5: print(i) # i += 1 is MISSING → runs forever!
# Want 1 to 5, but wrote: for i in range(5): print(i) # prints 0,1,2,3,4 NOT 1-5 # Correct: for i in range(1, 6): print(i) # prints 1,2,3,4,5 ✅
# ❌ Wrong — print is outside loop for i in range(3): x = i * 2 print(x) # prints only last value! # ✅ Correct — print is inside loop for i in range(3): x = i * 2 print(x) # prints all values ✅
Loops are one of the most powerful features in programming. They provide many advantages that make your code better, shorter, and smarter.
Loops are used everywhere in real programs. Here are practical examples showing how loops solve real-world problems.
prices = [50, 120, 30, 200, 75] total = 0 for price in prices: total += price print("Total Bill:", total)
users = ["Ali", "Sara", "John"] for user in users: print(f"Hello {user}! Welcome!")
Hello Sara! Welcome!
Hello John! Welcome!
attempts = 0 while attempts < 3: pwd = input("Password: ") if pwd == "1234": print("Access granted!") break attempts += 1 print("Wrong! Try again.") else: print("Account locked!")
scores = [85, 92, 78, 96, 88] highest = 0 for score in scores: if score > highest: highest = score print("Highest:", highest)
Loops are one of the most essential concepts in Python programming. They allow you to automate repetitive tasks, process data efficiently, and build powerful programs with very few lines of code. Mastering loops is a critical step in becoming a good programmer.
Use a for loop when you know how many times to repeat. Use a while loop when you repeat based on a condition. Use break to stop, continue to skip, and pass as a placeholder. Practice these daily and loops will become natural to you!
| Topic | Key Point |
|---|---|
| for loop | Iterates over sequence / range |
| while loop | Repeats while condition is True |
| break | Exits the loop immediately |
| continue | Skips current step only |
| pass | Empty placeholder |
| Nested loop | Loop inside another loop |
Comments
Post a Comment