Python Loops

Python Loops

In Python, loops are used to execute a block of code repeatedly as long as a condition is met or for a predefined number of iterations. There are two primary types of loops in Python: for loops and while loops.


1. for Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range).

Syntax:

  for variable in sequence:
  # Code to execute
  • variable: A placeholder that takes the value of each element in the sequence, one at a time.
  • sequence: The collection being iterated over.

Example 1: Iterating over a list

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

Output:

banana

cherry


Example 2: Using range()

The range() function generates a sequence of numbers.

  for i in range(5):  # Generates numbers from 0 to 4
   print(i)   

Output:

  • 0
  • 1
  • 2
  • 3
  • 4

Example 3: Iterating over a string

  for char in "Python":
    print(char)

Output:

  • p
  • y
  • t
  • h
  • o
  • n

2. while Loop

The while loop repeats a block of code as long as the given condition is True.

Syntax:

  while condition:
    # Code to execute
  • condition: A logical expression evaluated before each iteration. If it is True, the loop continues; otherwise, it stops.

Example 1: Basic while loop

  count = 0
  while count < 5:
      print(count)
      count += 1  # Increment to avoid infinite loop

Output:

  • 0
  • 1
  • 2
  • 3
  • 4

Example 2: Using break in a while loop

The break statement is used to exit the loop prematurely.

  count = 0
  while True:  # Infinite loop
      print(count)
      count += 1
      if count == 3:  # Exit when count reaches 3
          break

Output:

  • 0
  • 1
  • 2

Example 3: Using continue in a while loop

The continue statement skips the rest of the code in the current iteration and moves to the next iteration.

  count = 0
  while count < 5:
      count += 1
      if count == 3:
          continue  # Skip printing when count is 3
      print(count)

Output:

  • 0
  • 1
  • 2
  • 3
  • 4

Loop Control Statements

  • break: Exits the loop immediately.
  • continue: Skips the current iteration and moves to the next iteration.
  • else: Runs after the loop finishes, unless the loop is terminated by break.

Example of else in a loop

  for i in range(3):
      print(i)
  else:
      print("Loop finished")

Output:

  • 0
  • 1
  • 2
  • Loop finished

Nested Loops

You can place one loop inside another to handle multi-dimensional data.

Example: Nested for loop

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

Summary Table

Loop Type Use Case Example
for loop Iterating over sequences for item in list:
while loop Executing code while a condition is true while condition:
break Exit loop early if condition: break
continue Skip to next iteration if condition: continue
Nested loops Multi-dimensional iteration for i in range(x): for j in range(y):

These examples and syntax demonstrate the versatility of loops in Python for repetitive tasks.

Previous Next