Unlocking the Flow: Mastering Loops in Python

Loops in Python are like helpful assistants that save you time and effort. They are super useful when you need to do the same thing over and over again. Imagine you’re a chef making lots of cookies. Instead of cutting out each cookie shape one by one, you use a cookie cutter to make many cookies quickly. That’s what loops do for your code!

The concept of looping is fundamental in programming as it enables the execution of a code block multiple times. Python offers several methods for creating loops:

‘For’ Loop with a range

Think of the for loop as a musical march through a specified range of values. It is used to iterate over a sequence of numbers. It generates a sequence of numbers based on a start, stop, and step size, and then iterates through them.

for num in range(1,0): 
    print(num)

 

Output:

Beat: 1
Beat: 2
Beat: 3
Beat: 4

 

The first for loop runs over the range from 1 to 4 (inclusive). It prints "Beat: " followed by each number from the range.

‘For’ Loop with an iterable

Just as a dancer pairs graceful moves to a melody, the for loop partners with iterables – like lists or strings – to execute a sequence of actions. It is used to iterate over elements in a collection like a list, tuple, or string.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}s")

 

Output:

I like apples
I like bananas
I like cherries

 

The for loop iterates over the list of fruits and prints "I like" followed by each fruit's name.

‘While’ Loop

The while loop dances to the rhythm of a condition. It repeatedly executes a block of code as long as a specified condition remains true.

count =
while count < 5:
print("Count: {count}")
count += 1

 

Output:

Count: 0 
Count: 1
Count: 2
Count: 3
Count: 4

 

The while loop starts with count at 0 and continues as long as count is less than 5. It prints "Count: " followed by the current value of count and then increments count by 1 in each iteration. The loop stops when count becomes 5.

‘Nested’ Loops

‘Nested’ loops are loops inside other loops. They’re used to perform iterations within iterations.

for i in range(3):
   for j in range(2):
       print(f"i: {i}, j: {j}")

 

Output:

i: 0, j: 0 
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1

 

The ‘nested’ for loops run through the given ranges. The outer loop iterates over i from 0 to 2, and for each value of i, the inner loop iterates over j from 0 to 1. This results in all possible combinations of i and j being printed, giving the output shown above.

Using ‘break’ and ‘continue’

The break statement is like an emergency stop button. It’s like when you’re playing a game, and something unexpected happens, so you want to stop right away. The continue is like skipping a step and moving on to the next one.

for num in range(1, 11):
     if num == 5:
         break # Exit the loop when num is 5 
     print(num)

for num in range(1, 6):
     if num == 3:
        continue # Skip printing when num is 3
     print(num)

 

Output:

1
2
3
1
2
4
5

 

In the first for loop, the loop iterates from 1 to 10. When num becomes 5, the break statement is executed, causing the loop to exit immediately. Therefore, only the numbers 1, 2, 3, and 4 are printed before the loop exits.In the second for loop, the loop iterates from 1 to 5. When num becomes 3, the continue statement is executed, which skips the rest of the loop’s code for that iteration. As a result, the number 3 is not printed, but the numbers 1, 2, 4, and 5 are printed in the remaining iterations.

Using ‘else’ with loops

These are control statements that allow you to alter the flow of execution in loops. The else block in a loop acts as a closing bow to your performance. It executes once the loop has completed all iterations, or if the loop’s condition becomes false (in the case of a while loop). However, it won’t execute if the loop is exited using the break statement:

for i in range(5): 
   print(i)
else:
   print("Loop completed without breaks")

for j in range(3):
   if j == 1:
	  break
   print(j)
else:
   print("This won't be executed because of the break")

 

Output:

0
1
2
3
4
Loop completed without breaks
0

 

In the first for loop, the loop iterates from 0 to 4. It prints each value of i from 0 to 4. After the loop completes all iterations, the else block associated with the for loop is executed, printing "Loop completed without breaks". This is because the loop completed all iterations without encountering a break statement. In the second for loop, the loop iterates from 0 to 2. When j becomes 1, the if condition is met, and the break statement is executed. This causes the loop to exit prematurely, so only the value 0 is printed. Since the loop was exited using a break statement, the else block associated with this loop is not executed.

 


Related Tags: