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:

for i in range(3):
    print(i)

Output:

0
1
2

While Loop:

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

Example Syntax:

while condition:
    # Code to run

Example program:

count = 0
while count < 3:
    print(count)
    count += 1

Output:

0
1
2

Nested Loop:

A loop inside another loop.

Useful for working with multi-dimensional data structures.

Example Program:

for i in range(3):  # Outer loop
    for j in range(2):  # Inner loop
        print(i, j)

Output:

0 0
0 1
1 0
1 1

Loop Control Statements:

break:

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

Example Program:

for i in range(10):
    if i == 5:
        break  # Exit the loop when i equals 5
    print(i)

Output:

0
1
2
3
4

Continue:

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

Example Program:

for number in range(1, 6):
    if number == 3:
        continue  # Skips the rest of the loop when number is 3
    print(number)

Output:

1
2
4
5

Pass:

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

Example program:

for number in range(1, 6):
    if number == 3:
        pass  # Does nothing when number is 3
    print(number)

Output:

1
2
3
4
5

Post a Comment

0 Comments