Understanding "while loop" in Python | Python Tutorials | BeingSkilled

Understanding while Loop in Python

The while loop in Python repeatedly executes a block of code as long as a given condition is True. It’s useful when the number of iterations is not known in advance.

Basic Syntax

while condition:
    # code to execute repeatedly

Let’s explore the while loop with practical examples to understand its power and flexibility.

Example 1: Simple Counter

i = 0

while i < 5:
    print("Count:", i)
    i += 1

This prints numbers from 0 to 4.

Example 2: Waiting for a Condition

ready = False
attempts = 0

while not ready and attempts < 3:
    print("Trying...")
    attempts += 1
    if attempts == 3:
        ready = True

Loops until either ready is True or attempts reach 3.

Example 3: User Input Loop

command = ""

while command != "exit":
    command = input("Type 'exit' to quit: ")
    print("You typed:", command)

Keeps asking for input until user types 'exit'.

Example 4: Infinite Loop with Break

while True:
    response = input("Continue? (y/n): ")
    if response == "n":
        break

Creates an infinite loop until the user decides to break it.

Example 5: Countdown

count = 5

while count > 0:
    print("Countdown:", count)
    count -= 1

Counts down from 5 to 1.

Example 6: Skipping Iterations with Continue

num = 0

while num < 5:
    num += 1
    if num == 3:
        continue
    print(num)

Skips printing the number 3.

Example 7: Using else with while

x = 0

while x < 3:
    print("x is", x)
    x += 1
else:
    print("Loop finished")

The else block executes after normal loop completion.

Example 8: Validating a Password

password = ""

while not password:
    password = input("Enter password: ")

print("Password set")

Prompts until the user enters a non-empty password.

Example 9: Searching for an Item

items = [3, 8, 12, 7, 9]
i = 0

while i < len(items):
    if items[i] == 12:
        print("Found at index", i)
        break
    i += 1

Searches for the number 12 in the list.

Example 10: Loop With Multiple Conditions

balance = 100
withdrawal = 20

while balance >= withdrawal:
    balance -= withdrawal
    print("Remaining:", balance)

Withdraws until the balance is insufficient.


When to Use while Loops

  • When the number of iterations is not fixed.
  • When waiting for a condition to become true.
  • When repeatedly validating input or system status.

The while loop is a powerful way to build logic that adapts based on real-time conditions. With proper safeguards, it can make your Python programs smarter and more interactive.