Python Loops

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)
Run Code Copy

Output

apple
banana
cherry

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

  • For i in range()This tutorial has examples on how to execute a block of code for each number in the given range using For Loop.
  • For ElseThis tutorial is about For Else construct, its syntax, and examples on how to use For loop with an else block followed.

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
Run Code Copy

Output

apple
banana
cherry

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

  • Python While ElseWe can write a While Loop with an Else block followed. This tutorial covers syntax, and examples on how to write a while-else construct.

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.

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

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.

Code copied to clipboard successfully 👍