Loops in Python – In-Depth Guide
1. Why Use Loops?
Loops are used to repeat a block of code multiple times. Instead of writing repetitive code,
you use loops to:
• Iterate over items in a list or string
• Repeat a task a specific number of times
• Repeat a task until a condition is met
2. Types of Loops in Python
Loop Type Description
for loop Used to iterate over a sequence (like list, tuple, string, range)
while loop Repeats as long as a condition is True
3. The for Loop
Syntax:
for variable in sequence:
# block of code
Example 1: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Loop through a string
for letter in "hello":
print(letter)
Output:
h
e
l
l
o
Example 3: Using range()
for i in range(5):
print(i)
Output:
0
1
2
3
4
• range(start, stop, step) can also be used for custom ranges.
4. The while Loop
Syntax:
while condition:
# block of code
Example 1: Count from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Common Mistake: Infinite loop
i = 1
while i <= 5:
print(i) # Forgot to increment i => Infinite loop!
5. Loop Control Statements
✅ break
Used to exit the loop when a condition is met.
for i in range(10):
if i == 5:
break
print(i)
✅ continue
Skips the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
✅ else with loop
for i in range(5):
print(i)
else:
print("Loop finished")
📘 6. Nested Loops
Loops inside loops are used for more complex patterns.
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
EXERCISES
1. To-Do List Manager
Use Case: Looping through tasks and allowing user to manage them
tasks = []
while True:
print("\nTo-Do List:")
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
print("\nOptions:")
print("1. Add Task")
print("2. Remove Task")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == "1":
new_task = input("Enter the task: ")
tasks.append(new_task)
elif choice == "2":
task_num = int(input("Enter task number to remove: "))
if 0 < task_num <= len(tasks):
tasks.pop(task_num - 1)
else:
print("Invalid task number.")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid input.")
Concepts:
• while loop
• enumerate()
• List manipulation
2. Simple Calendar Event Viewer
Use Case: Display events for each day of the week
calendar = {
"Monday": ["Meeting at 10AM", "Lunch with Sarah"],
"Tuesday": ["Gym", "Call with client"],
"Wednesday": [],
"Thursday": ["Project deadline"],
"Friday": ["Team meeting"],
"Saturday": ["Grocery shopping"],
"Sunday": ["Relax and read"]
}
for day, events in calendar.items():
print(f"\n{day}:")
if events:
for event in events:
print(f" - {event}")
else:
print(" No events")
Concepts:
• Nested for loops
• Dictionary iteration
3. Grocery Bill Calculator
Use Case: Loop through items and calculate total price
items = {}
while True:
name = input("Enter item name (or 'done' to finish): ")
if name.lower() == "done":
break
price = float(input(f"Enter price for {name}: "))
quantity = int(input(f"Enter quantity for {name}: "))
items[name] = (price, quantity)
total = 0
print("\nYour Bill:")
for item, (price, qty) in items.items():
subtotal = price * qty
print(f"{item}: {qty} x ${price:.2f} = ${subtotal:.2f}")
total += subtotal
print(f"\nTotal Amount: ${total:.2f}")
Concepts:
• Loop until condition (while)
• Dictionary for structured data
• Arithmetic inside loop
4. Password Validator
Use Case: Loop until valid password is entered
python
Copy code
while True:
password = input("Create a password: ")
if len(password) < 8:
print("Password must be at least 8 characters.")
continue
if not any(c.isdigit() for c in password):
print("Password must contain at least one digit.")
continue
if not any(c.isupper() for c in password):
print("Password must contain at least one uppercase letter.")
continue
print("Password created successfully!")
break
Concepts:
• continue to skip invalid input
• any() and str methods
5. Loan Repayment Calculator
Use Case: Calculate monthly payments and track balance
python
Copy code
loan_amount = float(input("Enter loan amount: "))
monthly_payment = float(input("Enter monthly payment: "))
interest_rate = float(input("Annual interest rate (%): ")) / 100 / 12
month = 1
while loan_amount > 0:
interest = loan_amount * interest_rate
principal = monthly_payment - interest
if principal > loan_amount:
principal = loan_amount
loan_amount -= principal
print(f"Month {month}: Paid ${monthly_payment:.2f}, Interest:
${interest:.2f}, Remaining balance: ${loan_amount:.2f}")
month += 1
Concepts:
• while with financial logic
• Realistic application of interest and repayment
6. Bulk Email Sender (Simulation)
Good example to introduce automation.
emails = ["
[email protected]", "
[email protected]", "
[email protected]"]
for email in emails:
print(f"Sending email to {email}...")
# Simulated delay or actual send code here
print("Email sent successfully!\n")
In real-world apps, you'd use libraries like smtplib to send real emails.
7. Username and Password Verification System
Features:
• Only prompts for the password if the username exists
• Allows multiple attempts
• Uses a dictionary to store user data
• Shows proper messages for incorrect usernames or passwords
Code:
# Predefined users (username: password)
user_db = {
"alice": "Alice@123",
"bob": "BobSecure456",
"charlie": "Charlie$789"
}
MAX_ATTEMPTS = 3
# Step 1: Ask for username
for _ in range(MAX_ATTEMPTS):
username = input("Enter username: ").strip()
if username in user_db:
print(f"Welcome {username}! Please enter your password.")
# Step 2: Ask for password
for attempt in range(MAX_ATTEMPTS):
password = input("Password: ")
if password == user_db[username]:
print("Login successful! ✅")
break
else:
print("Incorrect password ❌")
if attempt < MAX_ATTEMPTS - 1:
print(f"Attempts left: {MAX_ATTEMPTS - attempt - 1}")
else:
print("Too many incorrect attempts. Access denied 🚫")
break # Exit the username loop if user found
else:
print("Username not found ❌")
else:
print("Too many incorrect usernames. Exiting... 🚪")
📌 What It Demonstrates:
• Nested for loops: outer for username, inner for password
• Use of break and else on loops
• Dictionary lookup
• Basic user authentication logic
8. Login with Visible Username Iteration
Here’s the updated version with print() to show the process of checking each username:
# User database (username: password)
user_db = {
"alice": "Alice@123",
"bob": "BobSecure456",
"charlie": "Charlie$789"
}
MAX_ATTEMPTS = 3
# Username check with visible iteration
for _ in range(MAX_ATTEMPTS):
username_input = input("Enter username: ").strip()
username_found = False
print("\nChecking usernames in database...")
for username in user_db:
print(f"Checking: {username}") # Show the current username being
checked
if username_input == username:
username_found = True
break
if username_found:
print(f"\n✅ Username '{username_input}' found. Please enter your
password.")
for attempt in range(MAX_ATTEMPTS):
password_input = input("Password: ")
if password_input == user_db[username_input]:
print("✅ Login successful!")
break
else:
print("❌ Incorrect password")
if attempt < MAX_ATTEMPTS - 1:
print(f"Attempts left: {MAX_ATTEMPTS - attempt - 1}")
else:
print("🚫 Too many incorrect attempts. Access denied.")
break # Stop asking for username if correct
else:
print("❌ Username not found.")
else:
print("🚪 Too many failed attempts. Goodbye.")
🧠 Explanation of print(f"Checking: {username}"):
This line lets you observe each iteration and see:
• Which username is currently being compared
• That the loop stops once a match is found (via break)