Loops in Python – while Loop

A loop allows you to execute a block of code repeatedly as long as a certain condition is met.

The while loop in Python is used when you want to repeat an action an unknown number of times — until a condition becomes false.


Basic Syntax of while Loop

while_syntax.py
while condition:
    # block of code

Explanation:

  • The condition is checked before each iteration.
  • If True, the block is executed.
  • If False, the loop ends.

Example 1: Simple Counter

while_counter.py
count = 1
 
while count <= 5:
    print("Count:", count)
    count += 1
output.txt
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation:

  • The loop runs until count exceeds 5.
  • count += 1 increments the counter each time.

Example 2: Input Validation Loop

while_input_validation.py
password = ""
 
while password != "python123":
    password = input("Enter the password: ")
 
print("Access granted!")
output.txt
Enter the password: abc
Enter the password: 123
Enter the password: python123
Access granted!

Explanation:

  • The loop keeps asking for input until the correct password is entered.
  • Very useful in login systems or user input validation.

Example 3: Summing Numbers Until Zero

while_sum.py
total = 0
num = int(input("Enter a number (0 to stop): "))
 
while num != 0:
    total += num
    num = int(input("Enter a number (0 to stop): "))
 
print("Total sum:", total)
output.txt
Enter a number (0 to stop): 5
Enter a number (0 to stop): 3
Enter a number (0 to stop): 2
Enter a number (0 to stop): 0
Total sum: 10

Explanation:

  • The loop reads numbers from the user.
  • It continues adding them to total until the user enters 0.

Example 4: Generating a Multiplication Table

while_multiplication.py
num = 7
i = 1
 
while i <= 10:
    print(f"{num} x {i} = {num * i}")
    i += 1
output.txt
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

Explanation:

  • This generates a multiplication table up to 10.
  • A common beginner task that demonstrates controlled repetition.

Example 5: Factorial of a Number

while_factorial.py
num = 5
factorial = 1
 
while num > 0:
    factorial *= num
    num -= 1
 
print("Factorial:", factorial)
output.txt
Factorial: 120

Explanation:

  • This computes n! using a while loop.
  • It demonstrates use of decrementing in a loop.

Example 6: Infinite Loop with break

while_infinite_break.py
while True:
    choice = input("Continue (y/n)? ")
    if choice == "n":
        break
    print("Looping...")
output.txt
Continue (y/n)? y
Looping...
Continue (y/n)? y
Looping...
Continue (y/n)? n

Explanation:

  • The loop is designed to run forever (while True).
  • The break statement is used to exit the loop when needed.
  • Useful in menu-driven applications or interactive scripts.

Example 7: Nested while Loop – Multiplication Grid

while_nested.py
i = 1
 
while i <= 3:
    j = 1
    while j <= 3:
        print(f"{i} x {j} = {i * j}", end="\t")
        j += 1
    print()
    i += 1
output.txt
1 x 1 = 1    1 x 2 = 2    1 x 3 = 3
2 x 1 = 2    2 x 2 = 4    2 x 3 = 6
3 x 1 = 3    3 x 2 = 6    3 x 3 = 9

Explanation:

  • A nested while loop allows creating multi-dimensional structures.
  • The outer loop controls rows, inner loop controls columns.
  • Demonstrates nested iteration.

Summary

  • The while loop runs as long as the condition is True.
  • It is perfect when you don’t know ahead of time how many iterations you need.
  • It works well for input validation, reading data, menu-driven programs, computing series, and generating sequences.
  • Be careful of infinite loops — always ensure the loop will eventually stop.
  • Complex structures can be built with nested while loops.

Next, we will explore the for loop — designed for iterating over sequences like lists, strings, tuples, and ranges.