Class: JSS / SSS (Adjustable per level)
Subject: Information and Communication Technology (ICT)
Topic: Python while Loops
Duration: 40 – 60 minutes
Sub-topics:
Understanding while loops
Infinite loops
break statement
else with while
The Guessing Game
---
1. Learning Objectives
By the end of this lesson, students should be able to:
✅ Understand the structure of a while loop
✅ Identify and avoid infinite loops
✅ Use the break statement to exit loops
✅ Understand and apply the else clause with loops
✅ Create an interactive guessing game in Python
---
2. Introduction to while Loop
The while loop is used to repeat a block of code as long as a condition is true.
Syntax:
while condition:
# code block
Example:
count = 1
while count <= 5:
print("Count is:", count)
count += 1
---
3. Infinite Loops
An infinite loop runs forever unless it is stopped manually or by a break
condition.
Example:
while True:
print("This will run forever unless we stop it!")
⚠ Warning: Infinite loops can freeze or crash your program if not controlled
properly.
---
4. The break Statement
The break statement is used to exit a loop before the condition becomes
false.
Example:
while True:
user_input = input("Type 'exit' to stop: ")
if user_input == "exit":
break
---
5. The else Clause in a while Loop
The else block runs only if the loop ends normally (not with a break).
Example:
x=1
while x <= 3:
print(x)
x += 1
else:
print("Loop ended without break")
---
6. The Guessing Game (Putting It All Together)
Let’s build a simple game using the concepts we've learned.
Code:
secret_number = 7
guess = 0
attempts = 0
max_attempts = 3
while attempts < max_attempts:
guess = int(input("Guess the number (1 to 10): "))
attempts += 1
if guess == secret_number:
print("🎉 Congratulations! You guessed it right.")
break
else:
print("❌ Wrong guess. Try again!")
else:
print("😢 Game Over! The number was", secret_number)
Explanation:
The loop runs for 3 attempts.
If the user guesses correctly, break ends the loop.
If the user fails all 3 attempts, the else block shows the correct answer.
---
7. Class Activities
🧠 Activity 1: Identify the output of given while loop examples.
💻 Activity 2: Modify the guessing game to give hints like "Too high" or "Too
low".
✍️Activity 3: Write your own number guessing game with 5 chances.
---
8. Summary
while loops are used for repeating tasks based on conditions.
Infinite loops can occur if no stopping condition is met.
The break statement is used to exit loops early.
The else clause runs if the loop ends normally.
Python games like Guessing Game make learning fun and interactive!
---
9. Homework / Assignment
Write a program that lets the user try to guess a word stored in a variable,
with only 4 attempts. Use while, if, break, and else.