Data Sci Lab 4
Data Sci Lab 4
Lab No: 04
OBE MARKS
Introduction:
Python, known for its simplicity and versatility, offers a range of control structures to manage the flow of
a program. Among these, the "while" loop is a fundamental construct that allows you to execute a block
of code repeatedly as long as a certain condition remains true. In this article, we'll delve into the world of
"while" loops in Python, exploring their basics, working mechanism, advantages, common use cases, and
practical examples.
while condition:
Code to be executed if the condition is true.
Example:
Here's a simple example that prints numbers from 1 to 5 using a "while" loop:
counter = 1
while counter <= 5:
print(counter)
counter += 1
In this example, the condition counter <= 5 is evaluated before each iteration. As long as it's true, the code
block within the loop is executed.
Initialization:
You start by initializing a variable or setting up the conditions that the loop relies on. This is usually done
before the loop itself.
Condition:
The loop continues to execute as long as the condition specified in the loop header remains true.
Iteration:
Inside the loop, you perform actions or changes that bring you closer to the condition becoming false.
This is often achieved through increments or decrements.
Procedure:
Describe the basic syntax of a while loop in Python.
while condition: Code to be executed repeatedly.
Explain that the loop starts by evaluating the "condition." If the condition is True, the code block
is executed. This process continues until the condition becomes False.
Define the initial value of variables used in the condition. False at some point to avoid infinite
loops.
Emphasize the indentation to maintain proper code structure.
Explain that while loops will continue to execute as long as the condition remains True.
Describe how to ensure the loop terminates, when necessary, for example, by modifying the
condition within the loop.
Examples:
Counting with a While Loop:
Suppose you want to count from 1 to 10. You can use a "while" loop for this purpose.
count = 1
while count <= 10:
print(count)
count += 1
Fig #4.1(counting with while loop)
Conclusion:
In Python, "while" loops are a powerful tool for iterating through code if a specified condition holds true.
They provide flexibility, allowing you to handle various scenarios, including user input validation,
repetitive tasks, and more. By understanding the basics and best practices of "while" loops, you can
harness their potential for efficient and effective programming.