Python Loops Explained: for Loop & while Loop with Examples (Beginner Guide)

Loops in Python

πŸ” Loops in Python
Complete Guide

for Loop · while Loop · Nested · break · continue · pass · Real-Life Uses

Section 01
Introduction to Loops

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.

πŸ’» Without Loop vs With Loop:
Python — Without Loop (bad)
print(1)

print(2)

print(3)

# ... 100 lines needed!
Python — With Loop (smart)
for i in range(1, 101):

    print(i)

# Just 2 lines — prints 1 to 100!
πŸ’‘ Key Idea: Loops are used whenever the same task needs to be repeated — printing, calculating, searching, or processing data.
Section 02
Types of Loops in Python

Python has two main types of loops — the for loop and the while loop. Each is used in different situations.

TypeUsed WhenExample
for loopYou know the number of timesLoop 5 times
while loopYou repeat until condition is FalseLoop until user quits
for loop — iterates over a sequence (list, range, string)
while loop — repeats as long as a condition is True
πŸ“Œ Python does NOT have a built-in do-while loop like C or Java. But you can replicate it using a while loop with a break.
Section 03
What is a for Loop?

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.

Iterates over any sequence — list, string, tuple, range
Automatically stops when the sequence ends
Counter is managed automatically by Python
Best used when the number of iterations is known
πŸ’‘ The variable in the for loop (like i) takes each value from the sequence one by one on every iteration.
Section 04
for Loop Syntax
πŸ“‹ Basic Syntax:
for variable in sequence: # code runs for each item statement
πŸ“‹ Using range():
for i in range(start, stop, step): statement
πŸ’» range() variations:
Python
# 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
⚠️ Important: The stop value in range() is NOT included. range(5) gives 0,1,2,3,4 — not 5.
Section 05
for Loop Examples
▶ Loop over a range:
Python
for i in range(1, 6):

    print(i)
πŸ‘† Output:
1
2
3
4
5
▶ Loop over a list:
Python
fruits = ["apple", "banana", "mango"]

for fruit in fruits:

    print(fruit)
πŸ‘† Output:
apple
banana
mango
▶ Loop over a string:
Python
for letter in "Python":

    print(letter)
πŸ‘† Output:
P
y
t
h
o
n
▶ Sum of numbers 1 to 10:
Python
total = 0

for i in range(1, 11):

    total += i

print("Sum:", total)
πŸ‘† Output:
Sum: 55
Section 06
What is a while Loop?

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.

Runs as long as the condition is True
You must manually update the counter/variable
Best when the number of iterations is unknown
Can run forever if condition never becomes False
⚠️ Danger: If you forget to update the variable, the while loop runs forever — called an infinite loop. Always make sure the condition will eventually become False!
Section 07
while Loop Syntax
πŸ“‹ Syntax:
while condition: # runs while condition is True statement # update variable here!
πŸ’» Basic Example:
Python
i = 1

while i <= 5:

    print(i)

    i += 1    # ← very important!
πŸ‘† Output:
1
2
3
4
5
πŸ’» while with else:
Python
i = 1

while i <= 3:

    print("Running:", i)

    i += 1

else:

    print("Loop finished!")
πŸ‘† Output:
Running: 1
Running: 2
Running: 3
Loop finished!
πŸ’‘ Both for and while loops support an else block — it runs once after the loop finishes normally.
Section 08
while Loop Examples
▶ Count down from 5:
Python
n = 5

while n > 0:

    print(n)

    n -= 1

print("Go!")
πŸ‘† Output:
5
4
3
2
1
Go!
▶ Sum until condition:
Python
total = 0

num   = 1

while num <= 5:

    total += num

    num   += 1

print("Total:", total)
πŸ‘† Output:
Total: 15
▶ Password check (repeat until correct):
Python
password = "1234"

attempt  = ""

tries    = 0

while attempt != password:

    attempt = input("Enter password: ")

    tries   += 1

print(f"Correct! Tries: {tries}")
πŸ’‘ This kind of loop is perfect for user input — it keeps asking until the right answer is given.
Section 09
Difference Between for and while Loop
Featurefor Loopwhile Loop
Based onSequence / rangeCondition
CounterAuto-managedManual update
Use whenCount is knownCount unknown
RiskNo infinite loopCan run forever
Shorter?Usually shorterCan be longer
ExamplePrint 1 to 10Wait for input
▶ Same task — two ways:
for loop
for i in range(1, 4):

    print(i)    # 1 2 3
while loop
i = 1

while i <= 3:

    print(i)    # 1 2 3

    i += 1
πŸ’‘ Both loops above give the same output, but the for loop is shorter. Use for when you know the count — use while when you don't.
Section 10
Loop Control Statements

Loop control statements change the normal flow of a loop. Python has three: break, continue, and pass.

StatementWhat it does
breakStops the loop completely and exits
continueSkips current iteration, goes to next
passDoes nothing — placeholder
▶ break — stop when 3 is found:
Python
for i in range(1, 6):

    if i == 3:

        break         # stop loop

    print(i)
πŸ‘† Output:
1
2
▶ continue — skip number 3:
Python
for i in range(1, 6):

    if i == 3:

        continue      # skip 3

    print(i)
πŸ‘† Output:
1
2
4
5
▶ pass — empty placeholder:
Python
for i in range(3):

    pass    # does nothing, no error

print("Done")
πŸ‘† Output:
Done
πŸ“ Important Notes:
break exits the loop — code after loop runs
continue skips only the current step — loop continues
pass is a placeholder for empty loops or functions
Section 11
Nested Loops in Python

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.

πŸ“‹ Syntax:
for i in outer_sequence: for j in inner_sequence: statement # runs i×j times
▶ Multiplication Table (3×3):
Python
for i in range(1, 4):

    for j in range(1, 4):

        print(i, "x", j, "=", i*j)
πŸ‘† Output:
1 x 1 = 1
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
▶ Star Pattern:
Python
for i in range(1, 5):

    print("* " * i)
πŸ‘† Output:
*
* *
* * *
* * * *
⚠️ Deeply nested loops (3+ levels) can be slow. Keep nesting to a maximum of 2 levels when possible.
Section 12
Common Mistakes in Loops

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:
Python — WRONG (infinite loop!)
i = 1

while i <= 5:

    print(i)

    # i += 1 is MISSING → runs forever!
❌ Mistake 2 — Off-by-one in range:
Python
# 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 ✅
❌ Mistake 3 — Wrong indentation:
Python
# ❌ 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 ✅
πŸ“ Key Rules to Avoid Mistakes:
Always update the counter in while loops
Remember range(n) starts from 0, not 1
Check indentation carefully — it changes logic
Test loops with small ranges first
Section 13
Advantages of Loops

Loops are one of the most powerful features in programming. They provide many advantages that make your code better, shorter, and smarter.

Saves time — write code once, run it thousands of times
Reduces code length — no need to repeat the same lines
Avoids errors — fewer repeated lines means fewer mistakes
Processes data — iterate over lists, files, and databases easily
Automation — automate repetitive tasks without manual effort
Flexible — works with any data type — list, string, dict, file
Works with break/continue — gives fine control over flow
🌟 Without loops, modern software — websites, apps, games, AI systems — would be impossible to build. They are the foundation of all programming logic.
Section 14
Real-Life Uses of Loops

Loops are used everywhere in real programs. Here are practical examples showing how loops solve real-world problems.

πŸ›’ 1. Shopping Bill Calculator
Python
prices = [50, 120, 30, 200, 75]

total  = 0

for price in prices:

    total += price

print("Total Bill:", total)
πŸ‘† Output:
Total Bill: 475
πŸ“§ 2. Send Message to All Users
Python
users = ["Ali", "Sara", "John"]

for user in users:

    print(f"Hello {user}! Welcome!")
πŸ‘† Output:
Hello Ali! Welcome!
Hello Sara! Welcome!
Hello John! Welcome!
πŸ” 3. Login Attempt Limit
Python
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!")
πŸ“Š 4. Find Highest Score
Python
scores  = [85, 92, 78, 96, 88]

highest = 0

for score in scores:

    if score > highest:

        highest = score

print("Highest:", highest)
πŸ‘† Output:
Highest: 96
Section 15
Conclusion

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!

TopicKey Point
for loopIterates over sequence / range
while loopRepeats while condition is True
breakExits the loop immediately
continueSkips current step only
passEmpty placeholder
Nested loopLoop inside another loop
🌟 Final Tip: Start by practising for loops with range(). Then move to while loops, nested loops, and loop control. With consistent practice, loops will become the easiest part of Python for you!
Python Loops for Loop while Loop Beginner
Python Loops — Automate, Repeat, and Build Smarter Programs!

Comments