Popular Searches
Popular Course Categories
Popular Courses

Introduction to Iteration and Looping

Introduction to Iteration and Looping

Loops and Iteration in Python

Introduction to Iteration and Looping in Python

Course: Python Training

Topic: Introduction to Iteration and Looping

Course Link: Python Training Course

Demo Registration: Register for a Free Course Demo

Academy Website: JustAcademy


1. Introduction

Iteration is the process of repeating a set of instructions multiple times. In programming, loops allow us to execute a block of code repeatedly without writing the same statements again and again. Python provides looping structures that make repetitive tasks easier, faster, and more maintainable.

For example, if you need to display the numbers from 1 to 100, writing 100 separate print statements would be inefficient. A loop can perform the same task with only a few lines of code.

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

Output:

1
2
3
4
5

This example uses a for loop to repeat the print() statement five times.

2. Learning Objectives

  • Understand the meaning of iteration and looping.
  • Learn why loops are important in programming.
  • Identify the main types of loops available in Python.
  • Understand how loop conditions and loop bodies work.
  • Explore iteration through strings, lists, ranges, and other collections.
  • Recognize infinite loops and common looping mistakes.
  • Use loops to solve basic programming problems.

3. What Is Iteration?

Iteration means performing a process repeatedly. In Python, each individual repetition of a loop is commonly called an iteration.

Consider this example:

print("Welcome")
print("Welcome")
print("Welcome")

The statement is repeated three times. The same result can be achieved more efficiently using a loop:

for count in range(3):
    print("Welcome")

Output:

Welcome
Welcome
Welcome

Here, the loop executes three iterations. The loop variable count takes the values 0, 1, and 2.

Key Characteristics of Iteration

  • Repetition: A block of code executes multiple times.
  • Control: The loop structure determines how repetition proceeds.
  • Termination: A loop generally finishes when its sequence is exhausted or its condition becomes false.
  • Efficiency: Repetitive tasks can be written with less duplicated code.

4. What Is a Loop?

A loop is a programming construct that repeatedly executes a block of statements. Loops are useful when working with lists, processing user input, calculating totals, searching for values, and automating repetitive operations.

Python primarily provides two looping statements:

Loop Type Purpose Typical Use
for loop Iterates over items in an iterable or through a sequence of values. Processing a list, string, tuple, or range.
while loop Repeats while a condition remains true. Repeating until a user enters valid input or a target condition is reached.

Python also provides statements such as break, continue, and pass that affect how loop bodies execute.

5. Understanding the Basic Loop Structure

A loop generally has a loop-control mechanism, a body of statements, and a way to determine whether another iteration should occur.

Example: Repeating a Message

for number in range(1, 4):
    print("Learning Python", number)

Output:

Learning Python 1
Learning Python 2
Learning Python 3

In this example:

  • for starts the loop.
  • number is the loop variable.
  • range(1, 4) produces the values 1, 2, and 3.
  • The indented print() statement is the loop body.
  • The loop finishes after all values have been processed.

6. Introduction to the for Loop

A for loop is used to iterate over an iterable object, such as a list, tuple, string, dictionary, set, or range. Python retrieves the next item from the iterable and executes the loop body for that item.

Syntax

for variable in iterable:
    # Statements to execute for each item
    statement

Example 1: Iterating Through a List

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Output:

Apple
Banana
Mango

The loop processes each item in the list, one at a time.

Example 2: Iterating Through a String

word = "Python"

for character in word:
    print(character)

Output:

P
y
t
h
o
n

A string is iterable, so the loop processes one character per iteration.

Example 3: Using range()

The range() function generates a sequence of integers commonly used with for loops.

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

Output:

1
2
3
4
5

The stop value, 6, is excluded. Therefore, range(1, 6) generates values from 1 through 5.

7. Introduction to the while Loop

A while loop repeatedly executes its body as long as its condition evaluates to True. The condition is checked before each iteration.

Syntax

while condition:
    # Statements to repeat
    statement

Example: Counting from 1 to 5

number = 1

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

Output:

1
2
3
4
5

The variable begins at 1. After each iteration, number += 1 increases its value. When it becomes 6, the condition number <= 5 is false and the loop ends.

Important: Ensure that a while loop can eventually reach a condition that evaluates to false, unless an intentionally continuous loop is required.

8. Difference Between for and while Loops

Feature for Loop while Loop
Control Iterates over an iterable. Continues while a condition is true.
Common use Processing items in a collection. Repeating until a condition changes.
Counter management Often handled automatically by the iteration process. May require manual updates to variables.
Risk of infinite repetition Usually low when iterating over a finite iterable. Higher if the condition never becomes false.
Example for item in items: while count < 5:

9. Understanding the Loop Flow

A loop follows a sequence of steps:

  1. The loop begins.
  2. Python obtains the next item or checks the loop condition.
  3. If the loop should continue, the indented body executes.
  4. Control returns to the iteration mechanism or condition check.
  5. The process repeats until the sequence ends or the condition becomes false.
  6. Execution continues with the statement after the loop.

Example: Tracking Iterations

for step in range(1, 4):
    print("Current step:", step)

print("Loop completed")

Output:

Current step: 1
Current step: 2
Current step: 3
Loop completed

The final message is outside the loop, so it executes once after all three iterations are complete.

10. Iterating Through Common Python Data Types

10.1 List Iteration

marks = [78, 85, 92]

for mark in marks:
    print(mark)

A list loop is useful for processing records, scores, names, prices, and other collections of values.

10.2 Tuple Iteration

coordinates = (10, 20, 30)

for coordinate in coordinates:
    print(coordinate)

Tuples are iterable and can be processed in the same way as lists.

10.3 Dictionary Iteration

student = {"name": "Asha", "age": 21}

for key, value in student.items():
    print(key, value)

Output:

name Asha
age 21

Using .items() allows a loop to access each key-value pair.

10.4 Set Iteration

colors = {"red", "green", "blue"}

for color in colors:
    print(color)

A set can be iterated over, but its iteration order should not be relied upon for a particular sequence.

11. Using a Counter in a Loop

A counter is a variable that tracks how many times a task has occurred or helps control repetition. Counters are especially common in while loops and counting algorithms.

count = 0

while count < 4:
    print("Iteration:", count + 1)
    count += 1

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

The counter increases by one on every iteration. If the update is removed, the condition remains true and the loop may continue indefinitely.

12. Accumulating Values with Loops

Loops can calculate totals by adding each value to an accumulator variable.

numbers = [10, 20, 30, 40]
total = 0

for number in numbers:
    total += number

print("Total:", total)

Output:

Total: 100

The variable total begins at zero. Each iteration adds one number to the current total. This pattern is useful for calculating sums, expenses, marks, quantities, and sales totals.

13. Loop Control Statements

13.1 The break Statement

The break statement immediately terminates the nearest enclosing loop.

for number in range(1, 6):
    if number == 4:
        break
    print(number)

Output:

1
2
3

When number reaches 4, the loop stops before printing it.

13.2 The continue Statement

The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output:

1
2
4
5

The number 3 is skipped, but the loop continues processing the remaining values.

13.3 The pass Statement

The pass statement does nothing. It acts as a placeholder when Python syntax requires a statement but the implementation is not ready.

for number in range(3):
    pass

print("Loop finished")

Output:

Loop finished

Unlike break and continue, pass does not stop or skip an iteration by itself.

14. Nested Loops: An Introduction

A nested loop is a loop placed inside another loop. For every iteration of the outer loop, the inner loop runs through its own iterations, unless control flow changes this behavior.

for row in range(1, 3):
    for column in range(1, 4):
        print("Row:", row, "Column:", column)

Output:

Row: 1 Column: 1
Row: 1 Column: 2
Row: 1 Column: 3
Row: 2 Column: 1
Row: 2 Column: 2
Row: 2 Column: 3

The outer loop runs twice and the inner loop runs three times for each outer iteration, producing six combinations. Nested loops are commonly used for tables, grids, matrices, and pattern printing.

15. Infinite Loops

An infinite loop is a loop that does not terminate naturally because its condition remains true or its execution path never reaches a terminating state.

Example of an Infinite Loop

count = 1

while count <= 5:
    print(count)
    # count is never increased

The condition remains true because count is always 1. The code therefore keeps printing 1 until execution is interrupted.

Corrected Version

count = 1

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

Updating the counter allows the condition to become false after the fifth iteration.

Common Reasons for Infinite Loops

  • Forgetting to update a counter variable.
  • Using a condition that can never become false.
  • Updating the wrong variable.
  • Writing a condition with an incorrect comparison operator.
  • Creating a loop where the exit condition is never reached.

16. Common Looping Errors and Best Practices

Error or Problem Why It Happens How to Avoid It
Infinite while loop The loop condition never becomes false. Check that relevant variables change correctly.
Incorrect range endpoint The stop value in range() is exclusive. Choose the start and stop values carefully.
Incorrect indentation Statements are placed outside or inside the loop unintentionally. Use consistent indentation, normally four spaces.
Unexpected skipped values A continue statement skips part of the loop body. Check the conditions controlling continue.
Unexpected early exit A break statement ends the nearest loop. Review where the statement is placed.
Unintended collection changes Items are removed or added while iterating over the same collection. Consider iterating over a copy or building a new collection.

Best Practices

  • Use a for loop when processing every item in a collection.
  • Use a while loop when repetition depends on a condition.
  • Keep loop bodies readable and focused on one task.
  • Use meaningful variable names such as student, price, or attempt.
  • Test loops with empty collections, one item, and multiple items.
  • Check boundary conditions, especially when using range().
  • Avoid unnecessary nested loops when a simpler approach is available.

17. Practical Applications of Iteration

  • Data processing: Read and process records from a collection.
  • Calculations: Compute totals, averages, and summaries.
  • Validation: Repeat input requests until the data is acceptable.
  • Searching: Examine items to find a target value.
  • Automation: Perform the same action on multiple files or records.
  • Reporting: Generate repeated rows or formatted output.
  • Education: Print patterns, tables, and number sequences.

Practical Example: Finding Even Numbers

numbers = [2, 7, 10, 13, 18, 21]

for number in numbers:
    if number % 2 == 0:
        print(number)

Output:

2
10
18

The loop checks each number. The modulo operator, %, returns the remainder after division. An even number has a remainder of zero when divided by two.

18. Exercises for Practice

Exercise 1: Print Numbers

Write a for loop that prints numbers from 1 to 10.

Exercise 2: Sum a Sequence

Use a loop to calculate the sum of the numbers from 1 to 5.

Exercise 3: Iterate Over a String

Write a loop that prints each character in the word "Python".

Exercise 4: Count Down

Use a while loop to print 5, 4, 3, 2, 1, and then print "Go!".

Exercise 5: Skip a Number

Print numbers from 1 to 10, but skip the number 5 using continue.

19. Exercise Solutions

Solution 1

for number in range(1, 11):
    print(number)

Solution 2

total = 0

for number in range(1, 6):
    total += number

print(total)

Output: 15

Solution 3

for character in "Python":
    print(character)

Solution 4

count = 5

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

print("Go!")

Solution 5

for number in range(1, 11):
    if number == 5:
        continue
    print(number)

20. Interview Questions and Answers

Q1. What is iteration in Python?

Answer: Iteration is the repeated execution of a process or block of code. In Python, loops provide a way to perform repeated operations.

Q2. What is a loop?

Answer: A loop is a control structure that repeatedly executes a block of code according to an iteration sequence or a condition.

Q3. What are the main types of loops in Python?

Answer: Python provides the for loop and the while loop.

Q4. What is the difference between a for loop and a while loop?

Answer: A for loop iterates over an iterable, while a while loop repeats as long as its condition is true.

Q5. What does range() do?

Answer: range() represents an arithmetic sequence of integers. It is commonly used with for loops. Its stop value is excluded.

Q6. What is an infinite loop?

Answer: An infinite loop is a loop that does not terminate naturally. It can occur when a condition remains true indefinitely.

Q7. What is the purpose of break?

Answer: break terminates the nearest enclosing loop immediately.

Q8. What is the purpose of continue?

Answer: continue skips the remainder of the current iteration and proceeds to the next one.

Q9. Can a loop iterate through a string?

Answer: Yes. A string is iterable, and a loop can process its characters one by one.

Q10. What is a nested loop?

Answer: A nested loop is a loop placed inside another loop. It is useful for working with grids, tables, and combinations of values.

21. Quick Revision

  • Iteration means repeating a process.
  • A loop executes a block of code repeatedly.
  • A for loop processes items from an iterable.
  • A while loop continues while its condition is true.
  • range() is commonly used to generate integer sequences.
  • break exits the nearest loop.
  • continue skips the remainder of the current iteration.
  • pass acts as a placeholder and performs no operation.
  • Nested loops place one loop inside another.
  • Correct indentation and termination conditions help prevent errors.

22. Conclusion

Iteration and looping are fundamental concepts in Python programming. They allow developers to process collections, repeat calculations, validate information, search for values, and automate repetitive tasks. Understanding the difference between for and while loops, along with loop control statements and common errors, provides a strong foundation for more advanced programming concepts.

Practice writing small loops, trace how variables change during each iteration, and test different boundary conditions to improve your confidence and problem-solving skills.


Learn Python with JustAcademy

Explore the course details and continue learning Python through JustAcademy.

whatsapp