Skip to content

For Loops

Basic Syntax

A for loop is used to iterate over a sequence (such as a list, tuple, string, or range).

python
for variable in sequence:
    # Code block to execute

Iterating Over a List

python
cities = ['New York', 'London', 'Tokyo']
for city in cities:
    print(f"I would like to visit {city}.")

Output:

I would like to visit New York.
I would like to visit London.
I would like to visit Tokyo.

Using range()

The range() function can be used to iterate a specific number of times.

python
for day in range(1, 8):
    print(f"Day {day}: Remember to stay hydrated!")

Behaviour of range()

Notice that the "stop" value is always exclusive. (Only 1 - 7) is printed

Output:

Day 1: Remember to stay hydrated!
Day 2: Remember to stay hydrated!
Day 3: Remember to stay hydrated!
Day 4: Remember to stay hydrated!
Day 5: Remember to stay hydrated!
Day 6: Remember to stay hydrated!
Day 7: Remember to stay hydrated!

Specifying Start, Stop, and Step in range()

python
for hour in range(0, 24, 6):
    print(f"It's {hour}:00 hours, time to check in.")

Output:

It's 0:00 hours, time to check in.
It's 6:00 hours, time to check in.
It's 12:00 hours, time to check in.
It's 18:00 hours, time to check in.

Iterating Over a String

python
message = "Hello"
for letter in message:
    print(f"Current letter: {letter}")

Output:

Current letter: H
Current letter: e
Current letter: l
Current letter: l
Current letter: o

Iterating Over a Dictionary

python
employee = {'name': 'John Doe', 'position': 'Developer'}
for key in employee:
    print(f"{key.capitalize()}: {employee[key]}")

Output:

Name: John Doe
Position: Developer

Using enumerate()

enumerate() adds a counter to an iterable.

python
tasks = ['Email clients', 'Update website', 'Plan meeting']
for index, task in enumerate(tasks, start=1):
    print(f"Task {index}: {task}")

Output:

Task 1: Email clients
Task 2: Update website
Task 3: Plan meeting

Using zip()

zip() combines multiple iterables.

python
students = ['Alice', 'Bob', 'Charlie']
grades = ['A', 'B+', 'A-']
for student, grade in zip(students, grades):
    print(f"{student} received a grade of {grade}.")

Output:

Alice received a grade of A.
Bob received a grade of B+.
Charlie received a grade of A-.

Nested Loops

python
departments = ['Sales', 'Development']
employees = ['Alice', 'Bob']
for department in departments:
    for employee in employees:
        print(f"{employee} works in {department}.")

Output:

Alice works in Sales.
Bob works in Sales.
Alice works in Development.
Bob works in Development.

break Statement

Exits the loop prematurely.

python
emails = ['[email protected]', 'invalid-email', '[email protected]']
for email in emails:
    if '@' not in email:
        print("Invalid email found, stopping process.")
        break
    print(f"Sending email to {email}")

Output:

Sending email to [email protected]
Invalid email found, stopping process.

continue Statement

Skips the current iteration.

python
usernames = ['admin', 'guest', 'user123']
for username in usernames:
    if username == 'guest':
        continue
    print(f"Welcome, {username}!")

Output:

Welcome, admin!
Welcome, user123!

Loop else Clause

The else block executes when the loop completes normally.

python
items_in_stock = ['apple', 'banana', 'orange']
for item in items_in_stock:
    print(f"{item} is available.")
else:
    print("All items have been listed.")

Output:

apple is available.
banana is available.
orange is available.
All items have been listed.

While Loops

Basic Syntax

A while loop repeats as long as a condition is true.

python
while condition:
    # Code block to execute

Simple While Loop

python
balance = 1000
withdrawal = 200
while balance > 0:
    print(f"Current balance: ${balance}")
    balance -= withdrawal
print("Account balance is zero.")

Output:

Current balance: $1000
Current balance: $800
Current balance: $600
Current balance: $400
Current balance: $200
Account balance is zero.

Input Validation Example

python
password = ''
while password != 'secret':
    password = input("Enter the password: ")
print("Access granted.")

Output:

Enter the password: 1234
Enter the password: password
Enter the password: secret
Access granted.

break Statement

Exits the loop when a condition is met.

python
attempts = 0
while True:
    response = input("Do you want to continue? (yes/no): ")
    if response.lower() == 'no':
        print("Exiting the program.")
        break
    attempts += 1
    print(f"Attempt {attempts}: Continuing the process.")

Output:

Do you want to continue? (yes/no): yes
Attempt 1: Continuing the process.
Do you want to continue? (yes/no): yes
Attempt 2: Continuing the process.
Do you want to continue? (yes/no): no
Exiting the program.

continue Statement

Skips to the next iteration.

python
orders = ['order1', 'cancel', 'order2']
index = 0
while index < len(orders):
    if orders[index] == 'cancel':
        index += 1
        continue
    print(f"Processing {orders[index]}")
    index += 1

Output:

Processing order1
Processing order2

Loop else Clause

Executes when the loop condition becomes false.

python
inventory = ['item1', 'item2', 'item3']
while inventory:
    item = inventory.pop()
    print(f"Sold {item}")
else:
    print("All items sold.")

Output:

Sold item3
Sold item2
Sold item1
All items sold.

Nested While Loops

python
floor = 1
while floor <= 3:
    room = 1
    while room <= 2:
        print(f"Cleaning room {room} on floor {floor}")
        room += 1
    floor += 1

Output:

Cleaning room 1 on floor 1
Cleaning room 2 on floor 1
Cleaning room 1 on floor 2
Cleaning room 2 on floor 2
Cleaning room 1 on floor 3
Cleaning room 2 on floor 3

Real-World Example: User Login Attempts

python
max_attempts = 3
attempts = 0
correct_pin = '1234'
while attempts < max_attempts:
    entered_pin = input("Enter your PIN: ")
    if entered_pin == correct_pin:
        print("PIN accepted. Access granted.")
        break
    else:
        attempts += 1
        print(f"Incorrect PIN. Attempts remaining: {max_attempts - attempts}")
else:
    print("Too many incorrect attempts. Card locked.")

Output:

Enter your PIN: 0000
Incorrect PIN. Attempts remaining: 2
Enter your PIN: 1111
Incorrect PIN. Attempts remaining: 1
Enter your PIN: 1234
PIN accepted. Access granted.

Understanding for and while loops is essential for controlling the flow of your Python programs. Use for loops when you need to iterate over a sequence, and while loops when you need to repeat actions until a condition changes.