Python While Loops

A while loop in Python repeatedly executes a block of code as long as a given condition is true.

Basic Syntax


while condition:
  # Code to be executed repeatedly
  # ...
    

The condition is evaluated before each iteration. If it's true, the code block is executed; otherwise, the loop terminates.

Example 1: Counting to 5


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

Output:


0
1
2
3
4
    

Example 2: Summing Numbers


numbers = [1, 2, 3, 4, 5]
total = 0
i = 0
while i < len(numbers):
  total += numbers[i]
  i += 1
print(f"The sum is: {total}")
    

Output:


The sum is: 15
    

Explanation: This example iterates through a list using a counter, accumulating the sum of elements.

Example 3: User Input Loop


while True:
  input_value = input("Enter a number (or 'quit' to exit): ")
  if input_value.lower() == 'quit':
    break
  try:
    number = int(input_value)
    print("You entered:", number)
  except ValueError:
    print("Invalid input. Please enter a number or 'quit'.")

    

Explanation: This example demonstrates a loop that continues until the user enters 'quit'. It also includes error handling to prevent the program from crashing if the user enters non-numeric input.

Example 4: Infinite Loop (Careful!)


#This is an infinite loop, avoid unless in specific scenarios
while True:
  print("This will run forever!")

This will print "This will run forever" continuously until manually stopped.

Important Note:

It's crucial to ensure that the condition in a while loop eventually becomes false to prevent infinite loops, which can cause your program to hang.