Python Loops: While Loop, For Loop, and Other Looping Concepts

1. While Loop

A while loop continues executing as long as a given condition is True. It checks the condition before running the code block inside the loop, and it stops once the condition becomes False.

Syntax:

while condition:
    # code block

Example:

count = 1
 while count <= 5:
     print(count)
     count += 1

2. For Loop

A for loop is used when you know in advance how many times the loop should run. It iterates over a sequence (such as a list, tuple, or string).

Syntax:

for item in sequence:
    # code block

Example:

fruits = ['apple', 'banana', 'cherry']
 for fruit in fruits:
     print(fruit)

3. Range with For Loop

The range() function is commonly paired with for loops to create a series of numbers.

Syntax:

for i in range(start, stop, step):
    # code block

Example:

for i in range(1, 6):
    print(i)

4. Nested Loops

A nested loop is a loop inside another loop. This enables more advanced iterations, such as looping through multi-dimensional structures like matrices or complex lists.

Syntax:

for i in range(3):
    for j in range(2):
        # nested loop code block

Example:

for i in range(3):
    for j in range(2):
        print(f"i = {i}, j = {j}")

5. Break and Continue Statements

The break statement allows a loop to terminate early, regardless of whether the loop's condition remains True.

Break:

for i in range(10):
    if i == 5:
        break
    print(i)

The continue statement is used to skip the rest of the code inside the loop for the current iteration and proceed to the next iteration.

Continue:

for i in range(5):
    if i == 3:
        continue
    print(i)