Introduction to Loops in Python | Types and Examples

 Definition of loop:

A loop in Python is a control flow statement that executes a block of code repeatedly until a specific condition is fulfilled.


Different types of loops in Python:

For Loop:

A for loop in Python is used to iterate over a sequence (like a list, tuple, or range) and execute a block of code for each item in that sequence.

Example syntax:

for item in sequence:

    # Code to run


Example program:



Output:


While Loop:

Repeats a block of code as long as a specified condition is true.


Example Syntax:

while condition:

    # Code to run


Example program:



Output:



Nested Loop:

A loop inside another loop.

Useful for working with multi-dimensional data structures.


Example Program:


Output:



Loop Control Statements:

break:

The break statement is used to immediately exit a loop when a certain condition is met.


Example Program:


Output:


Continue:

Skips the rest of the code inside the current loop iteration and moves to the next iteration.


Example Program:


Output:



Pass:

A placeholder that does nothing, used when you need to write a statement but have no action to take.


Example program:


Output:


Post a Comment

0 Comments