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
for varname in iterable_object:
----------------------------------------
indentation block of statements
----------------------------------------
# Other statements in programSyntax 2 — for..else loop
for varname in iterable_object:
----------------------------------------
indentation block of statements
----------------------------------------
else:
----------------------------------------
else block of statements
----------------------------------------
# Other statements in programExplanation
for,in, andelseare keywords.iterable_objectcan be:- Sequence:
bytes,bytearray,range,str - List types:
list,tuple - Set types:
set,frozenset - Mapping:
dict(iterates keys by default)
- Sequence:
- 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
forloop and runs theelseblock (if written). - Writing the
elseblock is optional.
Example 1 — while vs for over a string
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
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
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)
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)
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.
Loading playground…