⬅ Previous Next ➡

Loops and Iterations

While Loop (Iteration)
  • while repeats a block while condition is True.
  • Condition is checked before each iteration.
  • Be careful to update the variable to avoid infinite loop.
i = 1

while i         
For Loop (Iteration)
  • for loop is used to iterate over a sequence (list, string, tuple, etc.).
  • Commonly used with range() for numbers.
name = "PYTHON"

for ch in name:
    print(ch)
range() Function
  • range(stop) → 0 to stop-1
  • range(start, stop) → start to stop-1
  • range(start, stop, step) → step-wise sequence
for i in range(5):
    print(i)          # 0 1 2 3 4

for i in range(2, 6):
    print(i)          # 2 3 4 5

for i in range(10, 0, -2):
    print(i)          # 10 8 6 4 2
Nested Loops
  • Nested loop = loop inside another loop.
  • Used for patterns, tables, matrices, etc.
for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)
Loop Control Statements (break, continue, pass)
  • break → exits the loop immediately.
  • continue → skips current iteration and goes to next.
  • pass → does nothing (placeholder).
# break example
for i in range(1, 6):
    if i == 4:
        break
    print(i)          # 1 2 3

# continue example
for i in range(1, 6):
    if i == 3:
        continue
    print(i)          # 1 2 4 5

# pass example
for i in range(3):
    pass
else with Loops (for-else / while-else)
  • Loop else runs only when loop finishes normally.
  • If loop stops using break, else block will NOT run.
  • Useful for search programs.
# for-else example (search)
nums = [2, 4, 6, 8]
target = 5

for n in nums:
    if n == target:
        print("Found")
        break
else:
    print("Not Found")
Practical Program: Sum of First N Numbers (while)
  • Takes N as input and calculates sum from 1 to N using while loop.
n = int(input("Enter N: "))

i = 1
total = 0

while i         
Practical Program: Multiplication Table (nested for)
  • Prints multiplication table from 1 to 5 using nested loops.
for i in range(1, 6):
    for j in range(1, 6):
        print(i * j, end="\t")
    print()