Lesson 2: Loops

Loops are a fundamental concept in programming that allows you to execute a block of code repeatedly based on a certain condition or a sequence. Python provides two types of loops: the while loop and the for loop. Additionally, Python offers control flow statements like break, continue, and else that can be used within loops to control the flow of execution. This lesson will explore each of these in detail.

1. while Loop

The while loop repeatedly executes a block of code as long as a given condition is True. If the condition becomes False, the loop stops executing.

Syntax:
python
while condition:

# code to execute while condition is True

 

  • Condition: This is the expression that is evaluated before each iteration of the loop. If the condition evaluates to True, the block of code within the loop is executed.
  • Code block: This is the part of the loop that gets executed repeatedly as long as the condition is True.
Example:
python

counter = 1

while counter <= 5:

print(“Counter:”, counter)

counter += 1

 

Explanation:

  • The loop starts with counter = 1.
  • The condition counter <= 5is checked before every iteration. As long as counter is less than or equal to 5, the loop will continue.
  • In each iteration, the value of counteris printed, and counter is incremented by 1 (counter += 1).
  • The loop stops when counterexceeds 5, i.e., when the condition becomes False.

Output:

makefile
Counter: 1

Counter: 2

Counter: 3

Counter: 4

Counter: 5

 

Important Note:

It’s crucial to ensure that the condition eventually becomes False; otherwise, the loop will run indefinitely, leading to an infinite loop. For example, if we forget to increment counter, the loop would never stop.

2. for Loop

The for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in that sequence. Unlike the while loop, the for loop does not evaluate a condition continuously; instead, it loops through a fixed number of iterations based on the sequence provided.

Syntax:
python
for item in sequence:

# code to execute for each item

 

  • item: This represents the variable that takes the value of each element in the sequence on each iteration.
  • sequence: This is any iterable object (list, tuple, string, etc.) whose elements will be processed in the loop.
Example:
python
fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:

print(fruit)

 

Explanation:

  • The loop will iterate over the list fruits, and for each item (fruit) in the list, it will print the name of the fruit.
  • In each iteration, the variable fruittakes on the value of the current element from the list.

Output:

nginx
apple

banana

cherry

 

Using range() in for Loops

The range() function generates a sequence of numbers, which is often used in for loops to repeat a block of code a specific number of times.

Example:

python
for i in range(5):

print(i)

 

Explanation:

  • range(5)generates the numbers 0 through 4 (5 is excluded).
  • The loop iterates 5 times, printing the values 0, 1, 2, 3, and 4.

Output:

Output
0

1

2

3

4

 

3. break, continue, and else in Loops

Python provides three important control statements that can be used within loops to modify the flow of execution: break, continue, and else.

3.1. break Statement

The break statement is used to exit the loop prematurely, even if the loop’s condition has not yet been fully evaluated. This is typically used when a certain condition is met, and you no longer want to continue the loop.

Syntax:

python
while condition:

if some_condition:

break

# code to execute

 

Example:

python
counter = 1

while counter <= 5:

if counter == 3:

break

print(counter)

counter += 1

 

Explanation:

  • The loop starts with counter = 1and prints the value of counter until it reaches 3.
  • When counterequals 3, the break statement is executed, which causes the loop to stop.

Output:

Output
1

2

 

3.2. continue Statement

The continue statement is used to skip the current iteration and move to the next iteration of the loop. The remaining code within the loop is not executed for the current iteration.

Syntax:

python
while condition:

if some_condition:

continue

# code to execute for all iterations except the ones where the condition is true

 

Example:

python
counter = 0

while counter < 5:

counter += 1

if counter == 3:

continue  # Skip printing when counter is 3

print(counter)

 

Explanation:

  • The loop will print numbers 1 through 5, but when counter == 3, the continuestatement skips the print(counter) statement, so 3 is not printed.

Output:

Output

1

2

4

5

 

3.3. else in Loops

In Python, both for and while loops can have an optional else clause. The else block is executed when the loop has completed all its iterations without encountering a break statement. If a break is encountered, the else block is skipped.

Syntax:

python
for item in sequence:

# code to execute

else:

# code to execute if no break occurs

 

Example:

python
for i in range(5):

print(i)

else:

print(“Loop completed without a break.”)

 

Explanation:

  • The loop will print numbers 0 through 4.
  • Since there is no breakstatement in the loop, the else block is executed after the loop completes.

Output:

kotlin

0

1

2

3

4

Loop completed without a break.

 

Example with break:

python
for i in range(5):

if i == 3:

break

else:

print(“Loop completed without a break.”)  # This won’t be executed

 

Explanation:

  • The loop breaks when i == 3, so the elseblock is skipped.

Output:

Output

0

1

2

 

Conclusion

In this lesson, we learned about loops, which are essential for repetitive tasks in programming. Here’s a quick summary of what we covered:

  1. whileLoop: Executes a block of code as long as a condition is True.
  2. forLoop: Iterates over a sequence (list, range, etc.) and executes a block of code for each item in the sequence.
  3. breakStatement: Exits the loop prematurely.
  4. continueStatement: Skips the current iteration and moves to the next one.
  5. elsein Loops: Executes after the loop completes normally, without a break.

Loops and control flow statements give you fine control over the execution of your programs, allowing you to perform tasks efficiently and conditionally.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *