Grade VIII • Lecture Notes

Chapter 7: Advanced Python

The while Loop • Infinite Loop • Using else in Loops

Chapter Overview

Learning Objectives

By the end of this session, students should be able to:

  • Explain the purpose of the while loop.
  • Understand how a while loop executes repeatedly.
  • Write simple Python programs using a while loop.
  • Explain what an infinite loop is.
  • Identify the common cause of an unintended infinite loop.
  • Explain the use of else with Python loops.
  • Differentiate between normal loop completion and termination using break.

1. Quick Recap: What is a Loop?

A loop is a programming construct that allows a set of statements to be executed repeatedly.

Loops are useful when a task has to be performed multiple times. Python provides several ways to create loops, including the for loop and the while loop.

Example:

If we want to print the numbers from 1 to 5, we could write repeated print() statements. A loop allows us to perform the same task more efficiently.

2. The while Loop

The while loop repeatedly executes a block of statements as long as its condition remains True.

Basic Syntax

while condition:
    statement(s)

The condition is checked before every iteration of the loop. If the condition is True, the loop body executes. When the condition becomes False, the loop stops.

3. How Does a while Loop Work?

Start
Check Condition
True?
Execute Body
Check Again

If the condition becomes False, execution moves to the statement following the loop.

4. Example: Printing Numbers Using while

count = 1

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

Output

1
2
3
4
5

How It Works

  1. count starts with the value 1.
  2. Python checks whether count <= 5.
  3. If the condition is true, the value is printed.
  4. count is increased by 1.
  5. The condition is checked again.
  6. The loop stops when count becomes 6 because 6 <= 5 is false.

5. Why Must We Update the Loop Variable?

In many while loops, the condition depends on a variable whose value changes during each iteration.

count = 1

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

The statement count = count + 1 changes the value of count. Eventually the condition becomes false and the loop terminates.

Remember: When designing a while loop, always make sure that there is a clear path toward making its condition false, unless an infinite loop is intentionally required.

6. Example: while Loop with User Input

A while loop can be useful when the number of repetitions depends on user input.

number = 1

while number <= 3:
    name = input("Enter a name: ")
    print("Hello", name)
    number = number + 1

The loop asks for a name three times because the variable number is increased after each iteration.

7. What is an Infinite Loop?

An infinite loop is a loop that continues executing because its condition never becomes False.

Example

count = 1

while count <= 5:
    print(count)

This loop keeps printing 1 because the value of count is never changed.

Problem: Since count remains 1, the condition count <= 5 remains true forever.

8. Intentional Infinite Loops

Infinite loops are not always programming mistakes. Sometimes a program is intentionally designed to keep running until a particular event occurs.

while True:
    command = input("Enter command: ")

    if command == "quit":
        break

    print("You entered:", command)

Here, while True creates a loop whose condition is always true. The break statement provides a way to leave the loop when the user enters "quit".

Examples of situations where continuous loops may be useful:
  • Interactive command programs.
  • Game loops.
  • Systems that continuously monitor events.
  • Programs that wait for incoming tasks.

9. The break Statement

The break statement immediately terminates the nearest enclosing loop and transfers control to the statement following that loop.

while True:
    number = int(input("Enter a number: "))

    if number == 0:
        break

    print("You entered:", number)

The loop continues until the user enters 0. At that point, break terminates the loop.

10. Using else in Loops

Python allows an else block to be associated with both while and for loops. The else block executes when the loop finishes normally, without being terminated by break.

Syntax

while condition:
    statement(s)
else:
    statement(s)

11. Example: else with a while Loop

count = 1

while count <= 3:
    print(count)
    count = count + 1
else:
    print("Loop completed")

Output

1
2
3
Loop completed

The loop ends normally when the condition becomes false. Therefore, the else block executes.

12. What Happens When break is Used?

count = 1

while count <= 5:

    if count == 3:
        break

    print(count)
    count = count + 1

else:
    print("Loop completed")

Output

1
2

The loop is terminated by break when count becomes 3. Therefore, the else block does not execute.

Key Rule:

else in a loop means: "the loop completed normally", not simply "the condition became false at some point."

13. Normal Completion vs break

Situation Does the loop stop? Does else execute?
Loop condition becomes false Yes Yes
break is executed Yes No
Condition never becomes false and no break No — infinite loop No

14. Practical Example: Searching for a Number

A while loop with else can be useful when searching for a value.

numbers = [10, 20, 30, 40, 50]

target = 30
index = 0

while index < len(numbers):

    if numbers[index] == target:
        print("Number found!")
        break

    index = index + 1

else:
    print("Number not found.")

If the target is found, break terminates the loop and the else block is skipped.

If the loop reaches its normal end without finding the target, the else block executes.

15. while Loop vs for Loop

Feature while Loop for Loop
Control Usually controlled by a condition. Usually iterates over a sequence or iterable.
Number of repetitions Often not known in advance. Often determined by the iterable or range.
Common use Repeat while a condition remains true. Process items or repeat over a known range.
Infinite loop possibility Common if the condition never becomes false. Usually requires a deliberately unbounded iterable or other special construction.

16. Common Errors with while Loops

Error 1: Forgetting to Update the Variable

count = 1

while count <= 5:
    print(count)

Problem: count never changes, so the condition remains true.

Error 2: Updating in the Wrong Direction

count = 5

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

Here, the loop condition requires count to decrease, but the program increases it.

Error 3: Incorrect Indentation

Python uses indentation to define the body of a loop.

while count <= 5:
    print(count)
    count = count + 1
Tip: Be consistent with indentation. Four spaces are the standard convention for Python code blocks.

17. Classroom Activity: Trace the Loop

Study the following program and determine its output:

x = 2

while x <= 10:
    print(x)
    x = x + 2

else:
    print("Done")

Answer these questions:

  1. What is the initial value of x?
  2. How much does x increase each time?
  3. How many times does the loop body execute?
  4. Why does the else block execute?
  5. What would happen if the update statement were removed?

18. Think About It 🤔

  1. Why is a condition necessary in a while loop?
  2. What happens if the condition is always true?
  3. Why can an infinite loop sometimes be useful?
  4. What is the purpose of break?
  5. When does the else block of a loop execute?
  6. What is the difference between a loop ending normally and ending because of break?

19. Key Terms

Term Meaning
while loop A loop that repeatedly executes while its condition is true.
Iteration One execution of the body of a loop.
Infinite loop A loop that does not terminate because its condition never becomes false or because it is intentionally unbounded.
break A statement that immediately terminates the nearest enclosing loop.
else in a loop A block that executes when the loop completes normally, without executing break.
Condition An expression that evaluates to True or False and controls a while loop.

20. Chapter Recap

  • A while loop repeats a block of code while a condition is true.
  • The condition is checked before each iteration.
  • A loop variable often needs to be updated so that the loop can eventually terminate.
  • An infinite loop occurs when the loop does not reach a terminating condition.
  • while True can be used to create an intentionally continuous loop.
  • The break statement immediately terminates a loop.
  • The else block associated with a loop executes when the loop completes normally, without break.

21. Homework 📝

  1. Define a while loop and write its syntax.
  2. Write a Python program to print the numbers from 10 to 1 using a while loop.
  3. What is an infinite loop? Give one example.
  4. Explain the purpose of the break statement.
  5. Explain when the else block associated with a loop is executed.
  6. Write a Python program that prints the even numbers from 2 to 20 using a while loop.
  7. Write a program that repeatedly accepts numbers from the user and stops when the user enters 0.

22. Quick Assessment

  1. What is a while loop?
  2. When does a while loop stop?
  3. What is an infinite loop?
  4. What is the purpose of break?
  5. When does else execute with a loop?
  6. What happens to the loop's else block when break is executed?
  7. Write a Python program to print numbers from 1 to 5 using a while loop.