While loops
While Loops in Python
While loops are a key control structure in Python that let you execute a block of code repeatedly as long as a specific condition remains true. They're useful for performing tasks where the number of repetitions isn’t known in advance.
Syntax of a While Loop
-
The
conditionis evaluated before each iteration. -
If it's
True, the code block runs. -
When it becomes
False, the loop stops, and execution continues after the loop.
Importance of Indentation
In Python, indentation defines the block of code that belongs to the loop. All lines of code you want to repeat must be indented consistently, usually with four spaces.
Example: Printing “Great Blogs” Five Times
How It Works:
-
The variable
istarts at 0. -
As long as
i < 5, the program prints "Great Blogs" and incrementsiby 1. -
This continues until
ibecomes 5.
Output:
Modifying the Initial Value
Let’s start i from 1 instead:
Output:
The loop runs only 4 times now, as i begins at 1.
Infinite Loops
A common mistake is forgetting to update the loop condition, which can lead to an infinite loop:
This loop will run forever because i always remains less than 5.
When Are Infinite Loops Useful?
Sometimes, infinite loops are used intentionally. For example:
-
Servers waiting for incoming requests
-
Programs running until manually stopped
Here’s a simple example:
This loop runs until the program is manually interrupted.
User-Controlled Loop: Using Input
You can also use user input to decide how many times to run the loop:
How It Works:
-
The user enters a number
n. -
The loop prints "Great Blogs"
ntimes.
Example:
If the user inputs 4, the output will be:
Comments