MWZ

MINDWAREZONE

while Loop in python

The while loop checks a condition before each iteration. If the condition evaluates to True, the loop executes the code block. When the condition becomes False, the loop stops.

Syntax

while condition: 
    # code block
            

Key Points

  • Executes a block of code repeatedly while a condition is True.
  • The condition is checked before each iteration.
  • Stops when the condition becomes False.
  • Suitable when the number of iterations is unknown.
  • Can lead to an infinite loop if the condition never becomes False.
  • Often used with counters and user input validation.

Example 1: Print Numbers from 1 to 5

count = 1 
while count <= 5: 
    print(count) 
    count += 1
            

Output

1 
2 
3 
4 
5
            

Explanation

The loop starts with count = 1 and continues until count becomes greater than 5.

Example 2: Countdown Timer

number = 5 
while number > 0: 
    print(number) 
    number -= 1 
print("Time's up!")
            

Output

5 
4 
3 
2 
1 
Time's up!
            

Explanation

The loop decreases the value of number by 1 in each iteration until it reaches 0.

Example 3: User Password Check

password = "" 

while password != "python123": 
    password = input("Enter password: ") 

print("Access Granted")
            

Explanation

The loop continues asking for a password until the correct password is entered.

Infinite Loop Example

while True: 
    print("This loop never ends")
            

Explanation

Since the condition is always True, the loop runs indefinitely unless interrupted manually.

Common Mistakes

❌ Forgetting to update the loop variable:

count = 1 

while count <= 5: 
    print(count)
            

This creates an infinite loop because count never changes.

✅ Correct:

count = 1 

while count <= 5: 
    print(count) 
    count += 1
            

The while loop is a powerful control structure that allows code to be executed repeatedly based on a condition. It is especially useful when the number of iterations is not predetermined and depends on changing conditions.