Python While Loops

The while loop in Python is used to repeatedly execute a block of code as long as a condition is true. It's useful when the number of iterations is not known beforehand.

Example 1: Simple While Loop

Print numbers from 1 to 5.

# Simple while loop
count = 1
while count <= 5:
    print("Count:", count)
    count += 1

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

Example 2: Using While Loop with Else

Check if a number is less than 5 and print a message after the loop ends.

# While loop with else
number = 3
while number < 5:
    print("Number:", number)
    number += 1
else:
    print("Number is no longer less than 5.")

Number: 3

Number: 4

Number is no longer less than 5.

Example 3: Infinite Loop with Break

Continuously accept user input until 'exit' is entered.

# Infinite loop with break
while True:
    user_input = input("Enter a command ('exit' to quit): ")
    if user_input == 'exit':
        print("Exiting loop.")
        break
    else:
        print("You entered:", user_input)

Output Example:

Enter a command ('exit' to quit): hello

You entered: hello

Enter a command ('exit' to quit): exit

Exiting loop.

Example 4: Using Continue Statement

Print odd numbers less than 10.

# Using continue
number = 0
while number < 10:
    number += 1
    if number % 2 == 0:
        continue
    print("Odd Number:", number)

Odd Number: 1

Odd Number: 3

Odd Number: 5

Odd Number: 7

Odd Number: 9

Example 5: While Loop with User-Defined Condition

Simulate a countdown timer from 5 to 0.

# Countdown timer
import time
countdown = 5
while countdown >= 0:
    print("Countdown:", countdown)
    time.sleep(1)
    countdown -= 1
print("Liftoff!")

Countdown: 5

Countdown: 4

Countdown: 3

Countdown: 2

Countdown: 1

Countdown: 0

Liftoff!

Explanation: The while loop continues as long as the condition is true. The break statement exits the loop, and the continue statement skips to the next iteration.