What are Loops?

Loops allow you to repeat code multiple times. Python has two main loop types: for loops (iterate over sequences) and while loops (repeat while condition is true).

for Loop

Iterate over a sequence (list, string, etc.):

fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# orange

range() Function

Generate numbers for looping:

# Loop from 0 to 4
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# Loop from 2 to 9
for i in range(2, 10):
    print(i)  # 2, 3, 4, 5, 6, 7, 8, 9

# Loop with step
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

Looping with Index

Use enumerate() to get index and value:

fruits = ["apple", "banana", "orange"]

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

# Output:
# 0: apple
# 1: banana
# 2: orange

while Loop

Repeat while condition is True:

count = 0

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

# Output: 0, 1, 2, 3, 4

Loop Control

break - Exit Loop

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

continue - Skip Iteration

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # 1, 3, 5, 7, 9 (only odd numbers)

Nested Loops

Loops inside loops:

for i in range(3):
    for j in range(3):
        print(f"({i}, {j})")

# Output:
# (0, 0), (0, 1), (0, 2)
# (1, 0), (1, 1), (1, 2)
# (2, 0), (2, 1), (2, 2)

else with Loops

Execute code when loop completes normally (not with break):

for i in range(5):
    print(i)
else:
    print("Loop completed")

# If break is used, else block is skipped

Common Patterns

Sum numbers in list

numbers = [1, 2, 3, 4, 5]
total = 0

for num in numbers:
    total += num

print(total)  # 15

Find maximum value

numbers = [3, 7, 2, 9, 1]
max_value = numbers[0]

for num in numbers:
    if num > max_value:
        max_value = num

print(max_value)  # 9

Best Practices

  • Use for loops: Prefer for loops when you know the number of iterations
  • Avoid infinite loops: Ensure while loops have an exit condition
  • Use enumerate: When you need both index and value
  • List comprehensions: Consider comprehensions for simple transformations

Next Steps

Learn about lists and dictionaries to work with data in loops.