Module: Control Flow

While Loops

Python Programming: Control Flow - While Loops

While loops are a fundamental control flow statement in Python (and most programming languages). They allow you to repeatedly execute a block of code as long as a certain condition is true. This is incredibly useful when you don't know in advance how many times you need to repeat something.

Basic Syntax

while condition:
  # Code to be executed as long as the condition is true
  # ...
  • while keyword: Starts the while loop.
  • condition: An expression that is evaluated to a boolean value (True or False). The loop continues to execute as long as this condition remains True.
  • : (colon): Indicates the start of the code block that will be repeated.
  • Indented Code Block: The code that will be executed repeatedly. Indentation is crucial in Python! It defines the scope of the loop.

How it Works

  1. The condition is evaluated.
  2. If the condition is True, the code block inside the loop is executed.
  3. After the code block is executed, the condition is evaluated again.
  4. Steps 2 and 3 are repeated as long as the condition remains True.
  5. When the condition becomes False, the loop terminates, and the program continues with the next statement after the loop.

Example 1: Counting to 5

count = 1
while count <= 5:
  print(count)
  count += 1  # Increment the counter

Output:

1
2
3
4
5

Explanation:

  • count is initialized to 1.
  • The while loop continues as long as count is less than or equal to 5.
  • Inside the loop:
    • The current value of count is printed.
    • count is incremented by 1 (count += 1 is shorthand for count = count + 1).
  • Once count becomes 6, the condition count <= 5 is False, and the loop terminates.

Example 2: User Input Validation

user_input = ""
while user_input.lower() != "quit":
  user_input = input("Enter a command (or 'quit' to exit): ")
  print("You entered:", user_input)

print("Exiting program.")

Explanation:

  • The loop continues until the user enters "quit" (case-insensitive).
  • input() prompts the user for input.
  • user_input.lower() converts the input to lowercase for case-insensitive comparison.
  • The loop prints the user's input.
  • When the user enters "quit", the condition becomes False, and the loop terminates.

break Statement

The break statement allows you to exit a loop prematurely, even if the loop's condition is still True.

count = 1
while True:  # Infinite loop
  print(count)
  count += 1
  if count > 5:
    break  # Exit the loop when count is greater than 5

Output:

1
2
3
4
5

Explanation:

  • while True creates an infinite loop (it will run forever unless explicitly stopped).
  • The break statement inside the if condition terminates the loop when count becomes greater than 5.

continue Statement

The continue statement skips the rest of the current iteration of the loop and proceeds to the next iteration.

count = 0
while count < 10:
  count += 1
  if count % 2 == 0:  # If count is even
    continue  # Skip the rest of this iteration
  print(count)  # Only print odd numbers

Output:

1
3
5
7
9

Explanation:

  • The loop iterates from 1 to 10.
  • If count is even, the continue statement skips the print(count) line and goes to the next iteration.
  • Only odd numbers are printed.

Common Pitfalls: Infinite Loops

A common mistake with while loops is creating an infinite loop. This happens when the condition never becomes False.

# Example of an infinite loop (avoid this!)
count = 1
while count > 0:
  print(count)
  # Missing increment or decrement of count

This loop will print 1 forever because count is always greater than 0, and there's no code to change its value. Always ensure that something inside the loop modifies the condition so that it eventually becomes False.

else Clause with While Loops (Less Common)

Python allows an else clause with while loops. The else block is executed only if the loop completes normally (i.e., the condition becomes False without being interrupted by a break statement).

count = 1
while count <= 5:
  print(count)
  count += 1
else:
  print("Loop completed successfully!")

Output:

1
2
3
4
5
Loop completed successfully!

If you add a break statement inside the loop, the else block will not be executed.

When to Use While Loops

  • When you need to repeat a block of code until a specific condition is met, and you don't know in advance how many iterations are required.
  • For tasks like reading data from a file until the end of the file is reached.
  • For implementing interactive programs that continue running until the user explicitly quits.
  • For validating user input.

Summary

While loops are a powerful tool for controlling the flow of your Python programs. Understanding how they work, how to use break and continue, and how to avoid infinite loops is essential for writing effective and reliable code. Remember to always ensure your loop condition will eventually become False to prevent infinite loops.