Advanced Looping in Python: Detailed
Explanation with Examples
For Loop – Advanced Example
The for loop is generally used when you know how many times you need to iterate.
Example: Iterating Over a Multi-Dimensional List (Matrix)
Code:
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
for row in matrix:
for value in row:
if value % 40 == 0:
print(f"Found multiple of 40: {value}")
Explanation: Outer loop iterates over rows. Inner loop iterates over each value in the row.
Checks and prints if the number is a multiple of 40.
Nested For Loop – Advanced Example
Nested for loops are used to handle combinations or 2D data.
Example: Product and Region Combinations
Code:
products = ["Laptop", "Tablet", "Phone"]
regions = ["North", "South", "East", "West"]
for product in products:
for region in regions:
print(f"Sales report for {product} in {region}")
Explanation: Compares each product with every region (cross-combination). Used in multi-
dimensional analysis.
While Loop – Advanced Example
The while loop is used when the number of iterations is unknown and depends on a
condition.
Example: Simulating a Login System
Code:
correct_password = "python123"
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input("Enter your password: ")
if password == correct_password:
print("Login successful!")
break
else:
print("Incorrect password.")
attempts += 1
if attempts == max_attempts:
print("Account locked. Too many failed attempts.")
Explanation: Continues to ask for password until user enters the correct one or exceeds max
attempts.
Nested While Loop – Advanced Example
Useful for multi-level unknown conditions.
Example: ATM Cash Withdrawal Simulation
Code:
balance = 10000
while True:
print(f"Current balance: {balance}")
while True:
withdraw = int(input("Enter amount to withdraw (multiples of 500): "))
if withdraw % 500 == 0 and withdraw <= balance:
balance -= withdraw
print(f"Please collect your cash. New balance: {balance}")
break
else:
print("Invalid amount. Try again.")
continue_choice = input("Do you want to make another transaction? (yes/no): ")
if continue_choice.lower() != 'yes':
print("Thank you for using the ATM.")
break
Explanation: Outer while handles transaction continuation. Inner while handles correct
withdrawal condition.
Summary Table
Loop Type Purpose Example Use Case
For loop Fixed iteration Process each item in a list
Nested for Cross combinations, Region vs. Product analysis
matrices
While loop Unknown iteration count Login system, user input
validation
Nested while Multi-level conditions ATM simulation, multi-step
approvals