Lesson 11
Nested Loops — Inner and Outer Loop Patterns
Master Python nested loops: for-in-for, while-in-while, for-in-while, while-in-for. Build prime finders, validation, and marks reports.
Beginner35 min
Inner OR Nested loops
Defining one loop inside another loop is called an inner or nested loop.
Execution rule: For each value of the outer loop, the inner loop repeats for a finite number of times until the inner loop becomes false.
Python supports 4 approaches:
Approach 1 — for loop in for loop
for varname1 in iterable_object_1: # outer loop
for varname2 in iterable_object_2: # inner loop
# inner block
else:
# inner else
else:
# outer elsefor i in range(1, 6):
print("Val of i-outer loop=", i)
for j in range(1, 4):
print("\tVal of j-inner loop=", j)
else:
print("i am out-off inner loop")
else:
print("i am out-off outer loop")Approach 2 — while loop in while loop
while test_cond_1: # outer loop
while test_cond_2: # inner loop
# inner block
else:
# inner else
else:
# outer elsei = 1
while i <= 5:
j = 1
while j <= 3:
print("\tVal of j-inner loop=", j)
j = j + 1
else:
i = i + 1
print("i am out-off inner loop")
else:
print("i am out-off outer loop")Approach 3 — for loop in while loop
while test_cond_1: # outer loop
for varname2 in iterable_object_2: # inner loop
# inner block
else:
# inner else
else:
# outer elseApproach 4 — while loop in for loop
for varname1 in iterable_object_1: # outer loop
while test_cond_2: # inner loop
# inner block
else:
# inner else
else:
# outer elseExample — Prime numbers within a range
n = int(input("Enter the Range,In which Prime Numbers to display:"))
if n <= 1:
print("{} invalid input".format(n))
else:
nop = 0
nopsum = 0
for num in range(2, n + 1): # outer loop
res = True
for i in range(2, num): # inner loop
if num % i == 0:
res = False
break
if res:
print(num)
nop = nop + 1
nopsum = nopsum + num
else:
print("Number of Primes within {} Range={}".format(n, nop))
print("Sum of all Primes={}".format(nopsum))Example — Voter age validation (while True + break)
while True:
age = int(input("Enter age of Citizen:"))
if age >= 18 and age <= 100:
break
print("\t{} Invalid Age--try Again".format(age))
print("\t{} Years Age Citizen is Eligible to Vote".format(age))Example — Student marks report (validation + nested for)
while True:
sno = int(input("Enter Student Number:"))
if sno > 0:
break
print("\t{} is Invalid Student Number".format(sno))
while True:
urname = input("Enter Ur Name:")
if len(urname) == 0:
print("\tDon't enter space for Name--try again")
else:
words = urname.split()
res = "valid"
for word in words:
if not word.isalpha():
res = "invalid"
break
if res == "invalid":
print("{} is Invalid Name--try again".format(urname))
elif res == "valid":
break
# ... mark validation for CM, CPP, OS ...
# totmarks = cm + cppm + osm
# percent = round((totmarks / 300) * 100, 2)
# grade and report displayLoading playground…