Lesson 3.3: Loops – while Loop
Introduction:
The while loop in Python is used to execute a block of code repeatedly as long as a given condition remains true. Unlike the for loop, which iterates over a sequence, the while loop continues until the condition becomes false. This makes it ideal for scenarios where the number of iterations is not predetermined.
1. Syntax of while Loop:
Explanation:
-
The loop checks the condition before each iteration.
-
If the condition is
True, the code block executes. -
Once the condition becomes
False, the loop stops.
2. Example – Basic while Loop:
Output:
3. Example – Using while Loop for Input Validation:
4. Infinite Loops and Control:
-
A loop with a condition that never becomes
Falseis called an infinite loop. -
Use
breakto exit an infinite loop manually.
Example – Infinite loop with break:
Practical Tips:
-
Ensure the loop condition eventually becomes
Falseto avoid infinite loops. -
Combine
whileloops with counters or flags for controlled execution. -
Use
breakandcontinueto manage loop flow effectively.
Learning Outcome of This Lesson:
-
Understand the syntax and working of the
whileloop -
Use
whileloops for conditional repetition -
Handle infinite loops safely with
break -
Apply loops for real-world scenarios like input validation and repetitive tasks
