CS Pathfinder Logo CS Pathfinder

Unit 2 · Definite vs. Indefinite Loops

Definite vs. Indefinite Loops

Compare Python's loop categories to learn when to use definite loops (for) versus indefinite loops (while).

Introduction

In programming, many problems require the same task to be performed repeatedly. Instead of writing the same statements multiple times, programmers use loops. A loop executes a block of code again and again until a specific condition is met or until all elements in a sequence have been processed.

Python provides two major categories of loops:

  • Definite Loops (for loop) – Used when the number of iterations is already known before the loop starts.
  • Indefinite Loops (while loop) – Used when the number of iterations is not known in advance and depends on a condition.

Understanding the difference between these two loop types is extremely important because questions related to loop selection are commonly asked in university examinations, placement tests, competitive programming contests, and technical interviews.

A beginner often gets confused about when to use a for loop and when to use a while loop. Although both can repeat a set of statements, they are designed for different situations. Choosing the correct loop makes the program easier to read, easier to maintain, and less likely to contain logical errors.

Exam Point

Remember this simple rule:

If you know HOW MANY TIMES the loop should run → Use a for loop.

If you know WHEN the loop should stop but NOT how many times it will execute → Use a while loop.

Real-Life Analogy

  • Suppose your teacher asks you to write your name 20 times. Since the number is already known, this is similar to a definite loop (for).
  • Now imagine your teacher says, "Keep solving questions until the school bell rings." You do not know when the bell will ring, so this is similar to an indefinite loop (while).
Definite vs Indefinite loops
Figure 2.9 — Deciding between definite iteration and indefinite iteration paths.

Table of Contents

What is a Definite Loop?

A definite loop is a loop in which the number of repetitions is already known before execution begins. The program knows exactly how many times the loop body should execute. Because the number of iterations is predetermined, the loop automatically stops after completing all required iterations.

In Python, definite loops are implemented using the for statement. The for loop works by visiting each element of a sequence one by one. The sequence can be a list, tuple, string, dictionary, set, or a range of numbers generated using the range() function.

Every time the loop runs, the next element from the sequence is assigned to the loop variable. The statements inside the loop are then executed using that value. Once all elements have been processed, the loop terminates automatically without requiring any extra condition.

Important Characteristics

  • The number of iterations is known before execution.
  • Uses the for keyword.
  • Generally iterates over sequences or collections.
  • No separate update statement is required because Python automatically moves to the next element.
  • Safer than a while loop because accidental infinite loops are uncommon.

Syntax of a Definite Loop

for variable in sequence:
    statements

Here,

  • variable stores the current value during each iteration.
  • sequence can be a list, tuple, string, dictionary, set, or the output of range().
  • statements represent the block of code executed repeatedly.

Example 1: Printing Numbers

# Definite loop: repeats exactly 3 times

for i in range(3):
    print("Iteration:", i)

Output

Iteration: 0
Iteration: 1
Iteration: 2

Step-by-Step Execution

  1. range(3) generates the numbers 0, 1, 2.
  2. First iteration → i = 0.
  3. Second iteration → i = 1.
  4. Third iteration → i = 2.
  5. After all values are processed, the loop stops automatically.

Why Use range()?

The range() function generates a sequence of numbers without storing all numbers in memory at once. It is commonly used whenever we need to repeat a task a fixed number of times.

Example 2: Traversing a List

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

for fruit in fruits:
    print(fruit)
Apple
Mango
Orange

In this example, the loop runs exactly three times because there are three elements in the list. Python automatically assigns each fruit to the variable fruit during each iteration.

Common Mistakes

  • Forgetting the colon (:) after the for statement.
  • Incorrect indentation of the loop body.
  • Using range(n) expecting it to start from 1 (it starts from 0).
  • Confusing the loop variable with the sequence itself.

Exam Tip

In university examinations, if the question asks you to print numbers from 1 to N, traverse a list, print characters of a string, or repeat something a fixed number of times, the expected answer is almost always a for loop.

What is an Indefinite Loop?

An indefinite loop is a loop in which the number of iterations is not known before execution. Unlike a definite loop, the program cannot predict how many times the loop will execute. Instead, the loop continues running until a specified logical condition becomes False.

In Python, indefinite loops are created using the while statement. Before each iteration, Python checks a Boolean expression. If the expression evaluates to True, the statements inside the loop execute. As soon as the expression becomes False, the loop terminates automatically.

Since the stopping condition depends on values that change while the program is running, the exact number of repetitions cannot be determined beforehand. This makes the while loop highly suitable for situations involving user input, game loops, waiting for events, searching, password verification, or repeatedly reading data until a condition is satisfied.

Key Characteristics

  • The number of iterations is unknown before execution.
  • Uses the while keyword.
  • Execution depends on a Boolean condition.
  • The condition is checked before every iteration.
  • The loop stops only when the condition becomes False.
  • If the condition never becomes False, an infinite loop occurs.

Syntax of a While Loop

while condition:
    statements
    update expression

The update expression is extremely important because it changes the variables involved in the condition. Without updating these variables, the condition may never become False, resulting in an infinite loop.

Example 1: Counting Numbers

count = 1

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

Output

1
2
3
4
5

Step-by-Step Execution

  1. The variable count starts with value 1.
  2. Python checks whether count <= 5.
  3. The condition is True, so the number is printed.
  4. The value of count is increased by 1.
  5. The condition is checked again.
  6. This process repeats until count becomes 6.
  7. Now the condition becomes False and the loop terminates.

Example 2: User Controlled Loop

# Loop continues until user types exit

user_input = ""

while user_input != "exit":
    user_input = input("Type 'exit' to quit: ")

In this example, the programmer does not know how many times the user will enter values. One user may type exit immediately, while another may continue entering commands for several minutes. Therefore, this is an indefinite loop.

Real-Life Analogy

  • Keep studying until the examination starts.
  • Keep filling a water bottle until it becomes full.
  • Keep asking the user for a password until the correct password is entered.
  • Keep searching until the desired item is found.

Infinite Loop

An infinite loop occurs when the stopping condition never becomes False. In such cases, the loop continues forever unless it is manually stopped.

count = 1

while count <= 5:
    print(count)

This program never increases the value of count. Since count always remains 1, the condition count <= 5 is always True. As a result, the loop never terminates.

Common Mistakes

  • Forgetting to update the loop variable.
  • Writing the wrong logical condition.
  • Using assignment instead of comparison.
  • Creating accidental infinite loops.
  • Incorrect indentation.

Exam Tip

Whenever the question contains words such as "until", "keep repeating", "repeat while", "wait until", or "continue until", the expected answer is generally a while loop.

Detailed Comparison Table

Feature Definite Loop (for) Indefinite Loop (while)
Meaning Repeats a fixed number of times. Repeats until a condition becomes False.
Number of Iterations Known before execution. Unknown before execution.
Keyword for while
Works On Sequences or collections. Boolean conditions.
Condition Check Controlled by the sequence. Checked before every iteration.
Update Required No manual update required. Usually requires manual updates.
Infinite Loop Risk Very low. High if variables are not updated.
Common Uses Lists, strings, tuples, dictionaries, counting. Games, login systems, menus, searching, user input.

Memory Trick

  • FOR → Fixed Number
  • WHILE → Wait Until Condition Changes

How to Choose the Right Loop

Choosing between a for loop and a while loop depends entirely on the nature of the problem. Both loops can perform repetitive tasks, but one is usually more suitable than the other.

Selection Guide

  • Use a for loop when the number of iterations is already known.
  • Use a for loop when processing every element of a list, tuple, string, set, or dictionary.
  • Use a while loop when the stopping condition depends on user actions or changing data.
  • Use a while loop when the program must continue until a particular event occurs.

Quick Decision Table

Situation Recommended Loop
Print numbers from 1 to 100 for
Print every student name in a list for
Read password until correct while
Display menu until Exit is chosen while
Repeat a task exactly 20 times for

Summary

Python provides two primary loop structures: the for loop and the while loop. Although both are used for repetition, they solve different types of problems.

A for loop is called a definite loop because the number of iterations is known before execution. It is mainly used for traversing sequences and repeating operations a fixed number of times.

A while loop is called an indefinite loop because the number of iterations depends on a condition evaluated during program execution. It is suitable when the stopping point cannot be predicted in advance.

Key Takeaways

  • Loops eliminate repetitive code.
  • Use for when the number of repetitions is fixed.
  • Use while when repetition depends on a condition.
  • Always update variables inside a while loop.
  • Incorrect conditions can produce infinite loops.
  • Understanding loop selection is a frequently tested topic in university exams, coding interviews, and competitive programming.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.