For Loops

20 min In Progress

Learning Objectives

  • Iterate over sequences with for
  • Use range() to generate number sequences
  • Control loop flow with break and continue

Looping Over Sequences

A for loop repeats a block of code for each item in a sequence.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

The range() Function

range() generates a sequence of numbers. Use it when you need to repeat something a specific number of times.

for i in range(5):
    print(i)

# range(start, stop, step)
for i in range(2, 11, 2):
    print(i)

break and continue

break exits the loop entirely. continue skips the rest of the current iteration.

for num in range(10):
    if num == 3:
        continue
    if num == 7:
        break
    print(num)

Course Example: Summing Even Numbers

This script sums every even number from 2 to 100 using range with a step.

total = 0
for number in range(2,101,2):
 total += number
print(total)

Course Example: Nested Loops

You can place one loop inside another to work with combinations of values.

for even in range(2,11,2):
  for odd in range(1,11,2):
    val = even + odd
    print(even, "+", odd, "=", val)

📝 Exercise: Multiplication Table

Use a nested for loop to print a 5x5 multiplication table.

code.py
Output

            
← Back to Chapter