Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 07

for Loop and for..else — Iterate Over Collections

Use Python for loops over strings, lists, range, and dicts. Compare while vs for, build multiplication tables, find factors, and check perfect numbers.

Beginner40 min

for loop / for..else loop

Syntax 1 — basic for loop

python
for varname in iterable_object:
    ----------------------------------------
    indentation block of statements
    ----------------------------------------
# Other statements in program

Syntax 2 — for..else loop

python
for varname in iterable_object:
    ----------------------------------------
    indentation block of statements
    ----------------------------------------
else:
    ----------------------------------------
    else block of statements
    ----------------------------------------
# Other statements in program

Explanation

  • for, in, and else are keywords.
  • iterable_object can be:
    • Sequence: bytes, bytearray, range, str
    • List types: list, tuple
    • Set types: set, frozenset
    • Mapping: dict (iterates keys by default)
  • Each element of the iterable is selected, placed in varname, and the block executes. This repeats until all elements are processed.
  • When all elements are completed, PVM exits the for loop and runs the else block (if written).
  • Writing the else block is optional.

Example 1 — while vs for over a string

python
s = "PYTHON"

print("By using while loop")
i = 0
while i < len(s):
    print(s[i])
    i = i + 1

print("By using for loop")
for ch in s:
    print(ch)

Example 2 — Multiplication table with range

python
n = int(input("Enter a Number for Generating Mul Table:"))

if n <= 0:
    print("{} is Invalid Input".format(n))
else:
    for i in range(1, 11):
        print("{} x {} = {}".format(n, i, n * i))
    else:
        print("-" * 50)

Example 3 — Find factors of a number

python
num = int(input("Enter a Number for Finding Its Factors:"))

if num <= 0:
    print("{} is Invalid Input".format(num))
else:
    for i in range(1, (num // 2) + 1):
        if num % i == 0:
            print(i)
    print(num)

Example 4 — Perfect number check (for..else)

python
num = int(input("Enter a Number for Finding Its Factors:"))

if num <= 0:
    print("{} is Invalid Input".format(num))
else:
    s = 0
    for i in range(1, (num // 2) + 1):
        if num % i == 0:
            s = s + i
            print(i)
    else:
        res = "Perfect" if num == s else " Not Perfect"
        print("{} is {}".format(num, res))

Example 5 — Sum of digits (while inside for-style logic)

python
num = int(input("Enter a Number for Finding Digits Sum:"))

if num <= 0:
    print("{} is Invalid input".format(num))
else:
    s = 0
    while num > 0:
        digit = num % 10
        s = s + digit
        num = num // 10
    else:
        print("Sum of Digits=", s)

Knowledge check

Q1: What types can a for loop iterate over?
Answer: Any iterable — str, list, tuple, set, frozenset, dict, range, bytes, bytearray.

Q2: When does for..else execute else?
Answer: After all items are processed without break.

Next: File 08 — break Statement

Loading playground…