Skip to content

Loops

Many programming tasks require the same operation to be repeated many times. Rather than copying and pasting code, Python provides loops. A loop allows a block of code to run repeatedly, either for every item in a sequence or while a condition remains true.

Loops are fundamental in data science because datasets often contain many observations. A loop can process each observation, calculate values, update results, or automate repetitive tasks.

The for Loop

A for loop iterates over the items in a sequence. The loop variable temporarily stores each item, one at a time.

# A simple for loop over a list of marks

marks = [68, 72, 81, 59, 76]

for mark in marks:
    print("Student mark:", mark)

print("All marks have been printed.")

Processing Values inside a Loop

Loops become more useful when calculations are performed inside the loop body. The same calculation is applied to each item.

# Convert a list of returns into percentage form

returns = [0.02, -0.01, 0.035, 0.005]

for r in returns:
    percentage_return = r * 100
    print("Decimal return:", r)
    print("Percentage return:", percentage_return)
    print("----------------------")

Using range()

The range() function generates a sequence of numbers. It is often used when we need to repeat a task a fixed number of times.

# Print a sequence of years

for year in range(2020, 2026):
    print("Year:", year)

print("The loop has finished.")

The while Loop

A while loop repeats while a condition remains true. The programmer must ensure that the condition eventually becomes false.

# A while loop with a stopping condition

counter = 1

while counter <= 5:
    print("Iteration:", counter)
    counter = counter + 1

print("Loop finished.")

In the next activity, we introduce functions, which allow code to be organised into reusable blocks.