You're grading 30 student exams. Instead of writing the same calculation 30 times, you use a loop: for each exam, calculate the percentage, record the grade. Same logic, applied to every item in your list.

Print each element

Visit every element in a list, one by one.

print_all.py
nums = [10, 20, 30, 40, 50]

print("nums=" + str(nums))
for i in range(len(nums)):
    x = nums[i]

The loop runs once for each element. i is the index: 0, 1, 2, 3, 4.

for `for i in range(n)` - runs n times, i goes from 0 to n-1.
range `range(n)` gives numbers 0, 1, 2, ..., n-1.

Sum of a list

Add up all the numbers in a list.

sum.py
nums = [10, 20, 30, 40, 50]

print("nums=" + str(nums))
sum = 0

for i in range(len(nums)):
    sum = sum + nums[i]

Start with total = 0, then add each element one by one. This pattern is called an accumulator.

Count how many elements match

How many numbers are greater than 50?

count.py
nums = [35, 72, 48, 91, 56, 23, 88]

print("nums=" + str(nums))
count = 0
for i in range(len(nums)):
    if nums[i] > 50:
        count = count + 1

Use a counter variable, increment it when condition is met.

Fibonacci with a loop

Generate Fibonacci numbers using a loop instead of writing each line.

fibonacci.py
n = 
fib = [0] * n

fib[0] = 0
fib[1] = 1

for i in range(2, n):
    fib[i] = fib[i - 1] + fib[i - 2]

print("fib=" + str(fib))
n = 
fib = [0] * n

fib[0] = 0
fib[1] = 1

for i in range(2, n):
    fib[i] = fib[i - 1] + fib[i - 2]

print("fib=" + str(fib))
n = 
fib = [0] * n

fib[0] = 0
fib[1] = 1

for i in range(2, n):
    fib[i] = fib[i - 1] + fib[i - 2]

print("fib=" + str(fib))

The loop pattern: each element depends on the previous two. Loops let us express this once, then repeat it as many times as needed.

while `while condition:` - another way to loop, checks condition before each iteration.