While loop in python
General Structure of Python While Loop
The general structure involves three main components:
The loop condition,
The loop body, and
The update mechanism.
The loop condition is a boolean expression evaluated before each iteration to determine whether the loop should continue.
The loop body, defined by an indented block of code, contains the specific actions, operations, or instructions executed during each iteration.
The update mechanism, typically within the loop body, modifies the condition-related variables to ensure the loop eventually terminates. This setup allows for flexible, condition-based repetition and makes it easier to automate tasks that depend on dynamic or unpredictable criteria in a clear and controlled way.
General Syntax of Python While Loop
The general syntax consists of the while
keyword, followed by a boolean condition that evaluates to True or False. This is followed by a colon (:) and an indented block of code that defines the actions to be performed as long as the condition remains True, providing a clear and flexible way to execute repetitive tasks based on dynamic or conditional criteria.
Example Problems
Problem 1:
Write a while loop in Python that prints the first five positive odd numbers (1, 3, 5, 7, 9), each on a new line.
Solution
Problem 2:
Write a while loop that prints each word in the string "Hello World" after splitting it into words.
Solution:
The pass Keyword
In the context of a while loop, the pass keyword acts as a placeholder when no action is required for certain iterations, allowing the loop to continue running without interruption.
Example use of the pass
keyword
Problem 3:
Write a Python program that loops through numbers from 1 to 5 using a while loop, but does nothing inside the loop when the number is a multiple of 3. Print the number when it’s not a multiple of 3.
Solution:
Output:
The break
Keyword
In the context of a while loop, the break keyword is used to exit a loop prematurely. Normally, a while loop runs until its condition evaluates to False, but there are times when you may need to exit the loop before this condition is met.
This is particularly important in while loops because their termination depends on a condition that might not change naturally (e.g., in an infinite loop or when processing unpredictable data), making break essential to avoid unintended infinite execution or to optimize performance by stopping when a specific goal is achieved.
Examples use of the break keyword
Problem 4:
Given a starting number, write a while loop that increments a counter starting from 10 and searches for the first number divisible by 7. Once such a number is found, the loop should stop immediately using the break keyword. If found, print "Found a number divisible by 7, stopping the loop." Otherwise, print each number and stop at 20.
Solution:
Output:
The continue Keyword
In the context of a while loop, the continue keyword is used to skip the remaining body of the loop and move directly to re-evaluate the loop’s condition. It is typically used when you want to skip specific iterations based on a condition without exiting the loop entirely.
This is especially relevant in while loops, where iteration depends on a manually managed condition, and continue ensures that necessary updates to condition-related variables occur to prevent infinite loops or incorrect behavior. The purposes of the pass and continue keywords are often misunderstood, but a clear distinction is presented in the table below.
Problem 5:
Write a while loop that processes numbers from 1 to 12, printing only those numbers that are not divisible by 3. Use the continue keyword to skip numbers divisible by 3 without stopping the loop.
Solution:
Output:
Differences Between The Pass And Continue Keywords
Feature |
|
|
---|---|---|
Purpose | Skips the rest of the code in the current iteration and jumps to the next iteration of the loop. | Acts as a placeholder that does nothing; the loop continues normally. |
Effect | Alters the flow of the loop by skipping part of the loop body. | Does not alter the flow; used to maintain syntax when no code is required. |
Use Case | When you want to skip certain iterations based on a condition. | When you want to leave a block empty (e.g., to be implemented later or intentionally left blank). |
The While - Else clause
The while - else clause is a technique used to execute a block of code if and only if the while loop completes normally, without being interrupted by a break statement. In a while loop, the else block runs only if the loop’s condition evaluates to False naturally, indicating that the loop has finished its iterations without an early exit.
This construct is very useful in cases where you need to confirm that a loop completed successfully without interruption or skipping, it can be used to check if a condition was met or a search found no results, providing a clean way to handle post-loop logic without additional flags or checks.
Example to Illustrate
Output:
If a break were used (e.g., to exit at count == 3), the else block would be skipped, making this clause ideal for distinguishing between normal and interrupted loop termination.