While Loops

CSD1010: Week 2A
Wiedemann • Fall 2025

Sets & Input Validation

  • A set is an unordered collection of unique elements, defined with curly braces {}. (More on sets later.)
  • For now, we will use sets for input validation, the process of checking that input is an expected type/value.
  • Use in and not in to check set membership.
valid_commands = {"start", "help", "quit"}
command = input("Enter command: ").lower()

while command not in valid_commands:
    print("Invalid command.")
    command = input("Enter start, help, or quit: ").lower()

print(f"You chose: {command}")

While Loops

  • A while loop repeats code as long as its given condition is True.
  • Always ensure that the condition will eventually become False to avoid infinite loops.
  • If you accidentally make an infinite loop, press Ctrl+C in the terminal to stop it.
age = int(input("Enter your age: "))

while age < 0:
    print("Invalid age.")
    age = int(input("Enter your age: "))

print(f"Your age: {age}")

Counter Pattern

  • Counter pattern: Initialize a counter, then increment it each iteration.
  • Typically starts at 0 and counts up to (but not including) the target number.
  • Useful for repeating actions a pre-determined number of times.
count = 0

while count < 3:
    print("Doing something...")
    count = count + 1

print(f"Completed {count} iterations")

Accumulator Pattern

  • Accumulator pattern: Initialize a total, then add/multiply/etc. each iteration.
  • Combines counting with collecting/combining values.
total = 0
count = 0

while count < 5:
    value = int(input("Enter number: "))
    total = total + value
    count = count + 1

print(f"Sum of {count} numbers: {total}")

Sentinel Pattern

  • Sentinel pattern: Use a special "sentinel" value to signal when to stop looping.
  • Useful when you don't know in advance how many iterations are needed.
total = 0
number = int(input("Enter number (0 to quit): "))

while number != 0:
    total = total + number
    number = int(input("Enter number (0 to quit): "))

print(f"Total: {total}")

Flag Pattern

  • Flag pattern: Use a bool to control when the loop should end.
  • More flexible than sentinel values for complex stopping conditions.
is_playing = True
attempts = 0

while is_playing:
    guess = input("Guess the word: ")
    attempts = attempts + 1
    
    if guess == "python":
        print("You got it!")
        is_playing = False
    
    if attempts >= 5:
        print("You didn't get it :(")
        is_playing = False

Loop Control Statements

  • break: Immediately stop the loop.
  • continue: Skips the rest of the current iteration and goes back to the top of the loop.
  • else: Runs only if the loop completes without a break. Not used often.
count = 0

while count < 5:
    value = int(input("Enter number: "))
    
    if value < 0:
        continue  # Skip negative numbers
    if value > 100:
        break     # Exit if number too large
    
    print(f"Processing: {value}")
    count = count + 1
else:
    print("Processed all 5 numbers successfully")