Loops syntax

Loops are used to repeatedly execute a block of code as long as a specified condition is met. There are two main types of loops in Python: for loops and while loops. Each has its own syntax and use cases.

for Loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range). The basic syntax of a for loop is as follows:

for variable in sequence:
    # block of code to be executed

Example

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Using range()

The range() function is often used with for loops to generate a sequence of numbers.

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

Output:

0
1
2
3
4

Nested for Loops

You can nest for loops to iterate over multiple sequences.

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

Output:

i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1

while Loop

The while loop in Python repeatedly executes a block of code as long as a given condition is true. The basic syntax of a while loop is as follows:

while condition:
    # block of code to be executed

Example

count = 0

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

Output:

0
1
2
3
4

Infinite Loop

Be careful with while loops as they can create infinite loops if the condition never becomes false. You can use a break statement to exit the loop.

while True:
    print("This is an infinite loop!")
    break

Output:

This is an infinite loop!

Loop Control Statements

break

The break statement is used to exit a loop prematurely.

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

Output:

0
1
2
3
4

continue

The continue statement skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

Output:

1
3
5
7
9

else Clause in Loops

You can use an else clause with both for and while loops. The else block will be executed when the loop terminates naturally (i.e., not by a break statement).

for i in range(5):
    print(i)
else:
    print("Loop finished without break")

while count < 5:
    print(count)
    count += 1
else:
    print("While loop finished without break")

Output:

0
1
2
3
4
Loop finished without break
0
1
2
3
4
While loop finished without break

Summary

  • for Loop: Used for iterating over a sequence (list, tuple, string, range, etc.).
  • while Loop: Repeatedly executes a block of code as long as a condition is true.
  • Loop Control Statements:
    • break: Exits the loop.
    • continue: Skips the rest of the code inside the loop for the current iteration.
  • else Clause: Executes when the loop terminates naturally.