Loop Statements


Loop Statements

Loop statements help us to execute a block of code repeatedly in a loop until the given condition fails, or execute a block of code for each element in a given collection.

The following sections cover different looping statements, with description, reference to the full tutorial, and an example.

1. For Loop

For Loop is used to execute a block of code for each element in the given collection.

Complete tutorial: Python For loop

In the following program, we iterate over a list of strings, and print each string to output using For loop.

Python Program

list_1 = ['apple', 'banana', 'cherry']

for item in list_1:
    print(item)

Output

apple
banana
cherry

The following tutorials cover some of the scenarios dealing with For loop.

2. While Loop

While Loop is used to execute a block of code until a given condition fails.

Complete tutorial: Python While loop

In the following program, we iterate over a list of strings, and print each string to output using While loop.

Python Program

list_1 = ['apple', 'banana', 'cherry']

index = 0
while index < len(list_1):
    print(list_1[index])
    index += 1

Output

apple
banana
cherry

The following tutorials cover some of the use cases dealing with While loop.

  • Python - While else
    We can write a While Loop with an Else block followed. This tutorial covers syntax, and examples on how to write a while-else construct.
  • Python - Infinite While loop
    While loop where the condition is always true, the and the loop runs indefinitely until there is an interrupt.

Loop Controls

break and continue statements modify the behavior of a loop, either to exit the loop or to continue with the next items.

The following tutorials cover these statements in detail with examples.

  • Python - break
    Break statement can break the loop without the condition failure or iterator reaching the end of collection.
  • Python - continue
    Continue statement can skip the current block execution and continue with the next iteration.

Related Tutorials

Summary

In this tutorial, we learned about different loop statements in Python, loop control statement, and special cases of each of the loop statements, with examples.