Menu

Loops for Repetitive Data Tasks

Loops for Repetitive Data Tasks

Loops execute a block of code repeatedly. They are useful when processing collections, calculating totals, and applying the same operation to multiple values.

The for Loop

A for loop iterates over items in a sequence.

daily_sales = [1200, 1500, 900, 1800, 1600]

for sale in daily_sales:

print(sale)

You can calculate a total by accumulating values.

daily_sales = [1200, 1500, 900, 1800, 1600]

total_sales = 0

for sale in daily_sales:

total_sales += sale

print("Total sales:", total_sales)

For simple calculations, Python also provides built-in functions such as sum() and len().

total_sales = sum(daily_sales)

number_of_days = len(daily_sales)

average_sales = total_sales / number_of_days

print("Average daily sales:", average_sales)

The while Loop

A while loop continues as long as its condition remains true.

count = 1

while count <= 5:

print("Processing record", count)

count += 1

Be careful to update the condition inside a while loop. Otherwise, the loop may continue indefinitely.

For large datasets, ordinary Python loops can be less efficient than vectorized operations provided by libraries such as NumPy and Pandas. Loops remain useful for understanding the fundamentals and handling tasks that require step-by-step logic.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details