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.Python supports two main looping constructs: for loops and while loops.


1. for Loop

The for loop in Python loops allow sequential traversal of iterable objects such as lists, tuples, strings, and ranges.

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 creates an iterable sequence of numbers, commonly used in loops.

  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 continues running as long as the specified condition remains 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 stops the loop immediately, regardless of the original condition.

  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 allows the loop to skip the current iteration and move directly to the next one.

  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: statement forces the loop to jump to the next iteration, ignoring the remaining code in the current cycle.
  • 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