fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")I like apple
I like banana
I like cherry
Loops provide the ability to repeat a block of code multiple times, which is essential for tasks that require iteration over data structures or repeated operations. In data analytics, loops are fundamental for processing datasets, performing calculations on multiple items, and automating repetitive tasks. In this chapter, we will explore how to use loops effectively in Python.
There are two primary types of loops in Python: for loops and while loops. Each serves a different purpose and is used in different scenarios. Understanding when and how to use each type is crucial for writing efficient and readable code.
A for loop is used to iterate over a sequence (like a list, tuple, or string) or other iterable objects. It allows you to execute a block of code for each item in the sequence. This is particularly useful when you know exactly how many items you need to process or when you want to work with each element in a collection.
The syntax for a for loop is:
for variable in iterable:
# code to execute for each itemKey components explained:
variable: You can name this anything you like. It acts as a placeholder that takes on the value of each item in the iterable during each iterationiterable: This is the collection you want to loop through (list, tuple, string, etc.)for statement will be executed once for each item in the iterableYou can see it put to use in the following example. Notice that the variable fruit takes on the value of each item in the fruits list during each iteration of the loop.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")I like apple
I like banana
I like cherry
What happens step by step: 1. First iteration: fruit = “apple”, prints “I like apple” 2. Second iteration: fruit = “banana”, prints “I like banana”
3. Third iteration: fruit = “cherry”, prints “I like cherry” 4. Loop ends because there are no more items in the list
The for loop automatically handles moving from one item to the next, making it ideal for processing collections of data. In data analytics, you might use this to calculate statistics for each column in a dataset, process each row of data, or apply transformations to multiple variables. In fact, we can handle very large quantities of data with for loops, such as iterating through a DataFrame in pandas or processing large datasets in NumPy.
A while loop repeatedly executes a block of code as long as a specified condition remains true. Unlike for loops, which iterate over a known sequence, while loops continue until a condition changes. This makes them perfect for situations where you don’t know in advance how many iterations you’ll need.
The syntax for a while loop is:
while condition:
# code to execute while condition is trueCode explained: - condition: This is a boolean expression that is evaluated before each iteration - Loop body: The indented code block that executes when the condition is true - Update mechanism: You must include code that eventually changes the condition to false, or the loop will run forever
Here’s an example of a while loop that prints numbers from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 11
2
3
4
5
What happens step by step: 1. Initialize: count = 1 2. Check condition: Is 1 <= 5? Yes, so enter the loop 3. Print 1, then increment count to 2 4. Check condition: Is 2 <= 5? Yes, so continue 5. Print 2, then increment count to 3 6. This continues until count becomes 6 7. Check condition: Is 6 <= 5? No, so exit the loop
The crucial element here is count += 1, which increments the value of count by 1 in each iteration. This eventually causes the loop to terminate when count becomes 6, making the condition count <= 5 false. Warning: If you forget to update the variable that controls the condition, you’ll create an infinite loop that will never stop!
We could set a different condition if we wanted to stop the loop at a different point. For example, if we wanted to make the condition a boolean variable that could be set to True or False, we could do something like this:
running = True
count = 1
while running:
print(count)
count += 1
if count > 5:
running = False1
2
3
4
5
This example uses a boolean variable running to control the loop. The loop continues as long as running is True, and it stops when count exceeds 5, setting running to False. This approach is much more verbose than the last and is not recommended for simple counting tasks, but it illustrates how you can control the flow of a while loop with a boolean condition.
Use a for loop when: - You’re iterating over a known collection (list, tuple, string, etc.) - You know exactly how many iterations you need - You want to process each item in a sequence - You’re working with ranges of numbers
Use a while loop when: - You need to continue until a certain condition is met - You don’t know in advance how many iterations you’ll need - You’re waiting for user input or external conditions to change - You need more control over the loop’s termination condition
In data analytics, for loops are more commonly used because you’re often processing datasets with known structures, while while loops are useful for algorithms that need to continue until convergence or until certain statistical criteria are met.
When working with loops, we do not always want to loop over a collection of items. Sometimes we want to loop a specific number of times. The range() function is a built-in Python function that generates a sequence of numbers, which is particularly useful for creating loops that iterate a specific number of times. The range() function can take one, two, or three arguments, and its behavior changes based on the number of arguments provided:
range(n) generates numbers from 0 to n-1. Note that the last number is not included in the range.range(start, stop) generates numbers from start to stop-1.range(start, stop, step) generates numbers from start to stop-1, incrementing by step.Here’s how you can use the range() function in a for loop:
for i in range(5):
print(i)0
1
2
3
4
This loop will print the numbers 0 to 4, as range(5) generates the numbers 0, 1, 2, 3, and 4.