Loops#

Python provides two types of loops: for and while. for is used to iterate over iterable objects, while while keeps executing as long as a condition is true.


for Loop#

The for loop is used to iterate one by one over iterable objects (lists, strings, ranges, etc.):

1
2
3
4
5
6
7
8
9
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry

Iterating Over a String#

1
2
3
4
5
6
7
8
9
for char in "Python":
    print(char)

# P
# y
# t
# h
# o
# n

The range() Function#

range() generates a sequence of integers and is commonly used with for loops:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# range(stop): from 0 to stop-1
for i in range(5):
    print(i)   # 0 1 2 3 4

# range(start, stop): from start to stop-1
for i in range(2, 6):
    print(i)   # 2 3 4 5

# range(start, stop, step): specify the step size
for i in range(0, 10, 2):
    print(i)   # 0 2 4 6 8

# Negative step (count down)
for i in range(5, 0, -1):
    print(i)   # 5 4 3 2 1

enumerate() — Get Index and Value Simultaneously#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
fruits = ["apple", "banana", "cherry"]

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# 0: apple
# 1: banana
# 2: cherry

# Specify the starting index
for i, fruit in enumerate(fruits, start=1):
    print(f"Item {i}: {fruit}")

# Item 1: apple
# Item 2: banana
# Item 3: cherry

zip() — Iterate Over Multiple Sequences#

1
2
3
4
5
6
7
8
9
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(f"{name}: {score} points")

# Alice: 85 points
# Bob: 92 points
# Charlie: 78 points

while Loop#

The while loop keeps executing as long as the condition is True:

1
2
3
4
5
6
7
count = 0

while count < 5:
    print(count)
    count += 1

# 0 1 2 3 4

Common Pattern: Waiting for User Input#

1
2
3
4
5
6
7
while True:
    answer = input("Enter 'yes' to continue: ")
    if answer == "yes":
        break
    print("Please try again")

print("Continuing...")

break, continue, and else#

break: Exit the Loop#

1
2
3
4
5
6
for i in range(10):
    if i == 5:
        break
    print(i)

# 0 1 2 3 4

continue: Skip the Current Iteration#

1
2
3
4
5
6
for i in range(10):
    if i % 2 == 0:
        continue  # skip even numbers
    print(i)

# 1 3 5 7 9

else: Execute After the Loop Completes Normally#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# for...else: the else block runs if the for loop was NOT interrupted by break
for i in range(5):
    print(i)
else:
    print("Loop completed normally")

# When break is used, else does not execute
target = 7
for i in range(10):
    if i == target:
        print(f"Found {target}!")
        break
else:
    print(f"{target} not found")

Nested Loops#

Loops can be nested (a loop inside a loop):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} × {j} = {i * j}")
    print("---")

# 1 × 1 = 1
# 1 × 2 = 2
# 1 × 3 = 3
# ---
# 2 × 1 = 2
# ...

Multiplication Table#

1
2
3
4
for i in range(1, 10):
    for j in range(1, 10):
        print(f"{i}×{j}={i*j:2d}", end="  ")
    print()

List Comprehension#

List comprehension is built on the for loop — it borrows the loop syntax you just learned and “compresses” it into a single line inside square brackets:

1
2
3
4
5
6
7
8
# Traditional for loop
squares = []
for i in range(1, 6):
    squares.append(i ** 2)

# List comprehension: same logic, one line
squares = [i ** 2 for i in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

For the full syntax — filter conditions, if-else transforms, and nested comprehensions — see CH06: Lists.


Common Loop Techniques#

Sum and Aggregation#

1
2
3
4
5
6
7
8
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

total = sum(numbers)
average = total / len(numbers)
print(f"Sum: {total}, Average: {average}")

# Find max and min
print(f"Max: {max(numbers)}, Min: {min(numbers)}")

Using any() and all()#

1
2
3
4
5
6
7
8
9
scores = [85, 92, 78, 60, 95]

# any(): returns True if at least one element satisfies the condition
has_perfect = any(s == 100 for s in scores)
print(has_perfect)  # False

# all(): returns True only if all elements satisfy the condition
all_pass = all(s >= 60 for s in scores)
print(all_pass)  # True

Sorting and Reversing#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Sort (does not modify the original list)
sorted_nums = sorted(numbers)
print(sorted_nums)  # [1, 1, 2, 3, 4, 5, 6, 9]

# Sort in descending order
sorted_desc = sorted(numbers, reverse=True)
print(sorted_desc)  # [9, 6, 5, 4, 3, 2, 1, 1]

# Reverse iteration
for num in reversed(numbers):
    print(num, end=" ")