How do you achieve Loop Control in Python?

Loop control in Python is achieved through several mechanisms, including the use of break, continue, and else statements. These tools provide a way to manage the flow of loops, allowing programmers to execute or skip specific iterations based on conditions.

  1. break Statement:

The break statement is used to exit a loop prematurely when a specific condition is met. This is particularly useful when searching for an item in a list or terminating an infinite loop based on certain criteria. When break is executed, the loop is immediately terminated, and control is transferred to the statement following the loop.

for number in range(10):

    if number == 5:

        break

    print(number)

In this example, the loop prints numbers from 0 to 4 and exits when the number equals 5.

  1. continue Statement:

The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. This is useful when certain conditions need to be bypassed without exiting the entire loop.

for number in range(10):

    if number % 2 == 0:

        continue

    print(number)

Here, the loop prints only odd numbers from 0 to 9, as even numbers are skipped.

  1. else Clause:

The else clause in loops is executed when the loop completes normally, i.e., it is not terminated by a break statement. This feature is often used to detect whether the loop terminated naturally or prematurely.

for number in range(10):

    if number == 5:

        break

    print(number)

else:

    print(“Loop completed normally“)

In this example, the message “Loop completed normally” is not printed because the loop is terminated by the break statement when number equals 5.

  1. pass Statement:

The pass statement is a null operation; it is a placeholder used when a statement is syntactically required but no code needs to be executed. It is often used in loops when the loop body is yet to be implemented.

for number in range(10):

    pass  # Placeholder for future code

Leave a Reply

error: Content is protected !!