Loops and Iteration in Python

Loops are used to execute a block of code repeatedly. Python supports two types of loops:

  • for loop
  • while loop

The for Loop

The for loop in Python is used to iterate over a sequence (e.g., list, tuple, string) or other iterable objects.

Syntax

for variable in sequence:
    # Code to execute in each iteration

Example: Iterating Over a List

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

Example: Using range()

The range() function generates a sequence of numbers.

for i in range(5):
    print(i)  # Output: 0, 1, 2, 3, 4

You can also specify a start, stop, and step:

for i in range(1, 10, 2):
    print(i)  # Output: 1, 3, 5, 7, 9

The while Loop

The while loop executes as long as the condition is True.

Syntax

while condition:
    # Code to execute while the condition is True

Example: Counting Down

count = 5
while count > 0:
    print(count)
    count -= 1

The while...else Construct

In Python, a while loop can have an else clause that executes after the loop condition becomes False (unless the loop is terminated by a break statement).

Syntax

while condition:
    # Code to execute while the condition is True
else:
    # Code to execute when the loop ends naturally

Example: Checking Prime Numbers

num = 29
is_prime = True

if num > 1:
    i = 2
    while i < num:
        if num % i == 0:
            is_prime = False
            break
        i += 1
    else:
        print(f"{num} is a prime number.")

if not is_prime:
    print(f"{num} is not a prime number.")

Breaking Out of Loops

You can use the break statement to exit a loop prematurely.

Example

for i in range(10):
    if i == 5:
        break
    print(i)  # Output: 0, 1, 2, 3, 4

Skipping Iterations

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

Example

for i in range(5):
    if i == 2:
        continue
    print(i)  # Output: 0, 1, 3, 4

The pass Statement

The pass statement is a placeholder used in situations where a loop or block of code is syntactically required but no action is desired.

Syntax

for variable in sequence:
    pass

Example: Placeholder for Loop Logic

for i in range(5):
    pass  # Placeholder for future implementation

This is useful during development when you are outlining the structure of your code but haven’t implemented specific logic yet.


The else Clause with Loops

Loops in Python can have an else clause, which executes after the loop completes normally (i.e., not terminated by break).

Example

for i in range(5):
    print(i)
else:
    print("Loop completed.")

Nested Loops

You can place one loop inside another to iterate over multi-dimensional data structures or perform repeated operations.

Example

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

Infinite Loops

A while loop can become infinite if the condition never becomes False. Use caution to avoid such cases.

Example

while True:
    print("This is an infinite loop")
    break  # Use break to exit the loop

Task

Practice: Loops in Python

Objective: Write Python scripts using for and while loops to solve problems.

  1. Create a Python Script: Create a file named loops.py.

  2. Print Multiplication Table: Write a program that prints the multiplication table for numbers 1 to 10 using nested for loops.

for i in range(1, 11):
    for j in range(1, 11):
        print(f"{i} x {j} = {i * j}")
  1. Sum of Numbers: Write a program to calculate the sum of all numbers from 1 to 100 using a while loop.
total = 0
num = 1
while num <= 100:
    total += num
    num += 1
print(total)
  1. Guessing Game: Write a program where the user has to guess a random number between 1 and 50. The program should keep asking until the user guesses correctly or chooses to quit.

  2. Pattern Printing: Write a program to print the following pattern using nested loops:

*
**
***
****
*****

Copyright © 2025 Devship. All rights reserved.

Made by imParth