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

while condition: statement1 statement2
  • The condition is 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

i = 0 while i < 5: print("Great Blogs") i = i + 1

How It Works:

  • The variable i starts at 0.

  • As long as i < 5, the program prints "Great Blogs" and increments i by 1.

  • This continues until i becomes 5.

Output:

Great Blogs
Great Blogs Great Blogs Great Blogs Great Blogs

Modifying the Initial Value

Let’s start i from 1 instead:

i = 1 while i < 5: print("Great Blogs") i = i + 1

Output:

Great Blogs Great Blogs Great Blogs Great Blogs

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:

i = 0 while i < 5: print("Great Blogs") # i is never incremented

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:

while True: print("Great Blogs")

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:

n = int(input("Enter a number: ")) i = 0 while i < n: print("Great Blogs") i = i + 1

How It Works:

  • The user enters a number n.

  • The loop prints "Great Blogs" n times.

Example:
If the user inputs 4, the output will be:

Great Blogs Great Blogs Great Blogs Great Blogs

Comments

Popular Posts