COS 102

While Loops & Control Flow

Learn about While Loops & Control Flow in BIO 107. Comprehensive study materials and practice questions.

Study notes included Document available CBT practice ready

Study Document

Open full

Study Notes

COS 102

COS102: While Loops & Control Flow – Study Summary

1. Learning Outcomes

  • Understand the concept of Iteration.
  • Master the while loop syntax and flow.
  • Identify the causes of Infinite Loops.
  • Use the break statement for emergency exits.
  • Build interactive programs that wait for correct input.

2. The Need for Repetition (Iteration)

Computers excel at performing the same task repeatedly without fatigue. This is called iteration.

Examples:

  • Checking for new emails every minute.
  • Repeating music in a playlist.
  • Waiting for a user to type the correct PIN.

"Iteration saves you from writing the same code 1,000 times."

3. Anatomy of a While Loop

A while loop repeatedly executes a block of code as long as a specified condition is true.

while condition:
    # do something
    # update variable
  • while: The keyword to start the loop.
  • Condition: A boolean expression that must be True for the loop to run.
  • Update: Essential to modify the condition, eventually making it False to prevent infinite loops!

Flowchart Symbols Explained:

  • Oval (Start/end): Represents a start or end point.
  • Arrows: Connectors showing relationships between shapes.
  • Parallelogram (Input/Output): Represents input or output operations.
  • Rectangle (Process): Represents a process or action.
  • Diamond (Decision): Indicates a decision point (e.g., the loop's condition).

4. First Example: Counting

count = 1
while count <= 5:
    print("Number:", count)
    count = count + 1

Execution Flow:

  1. Check: Is 1 ≤ 5? (True) → Print "Number: 1", update count to 2.
  2. Check: Is 2 ≤ 5? (True) → Print "Number: 2", update count to 3.
  3. ...and so on until count is 6.
  4. Check: Is 6 ≤ 5? (False) → Loop terminates.

5. ATM Security Check (Interactive Example)

This demonstrates waiting for correct user input.

pin = ""
while pin != "1234":
    pin = input("Enter PIN: ")
print("Access Granted!")

This loop runs forever until the correct PIN "1234" is entered by the user. The loop's condition pin != "1234" becomes False only when the user types the correct PIN.

6. The Infinite Loop

An Infinite Loop occurs when the loop's condition never becomes False.

This usually happens if you forget to update your variable inside the loop, preventing the condition from ever changing to False.

i = 1
while i <= 5:
    print(i)
    # FORGOT i = i + 1!  <-- This would cause an infinite loop

In the example above, if the line i = i + 1 is forgotten, i will always be 1, making i <= 5 perpetually True.

7. Stopping a Runaway Loop (Emergency Stop)

If your program is stuck in an infinite loop:

  • Press Ctrl + C in your terminal/console.
  • This sends an interrupt signal to stop the program immediately.

8. The "break" Statement

Sometimes you need to exit a loop instantly, even if the condition is still True.

while True:
    msg = input("Type 'stop': ")
    if msg == "stop":
        break
print("Loop exited!")

In this example, the loop condition while True is always true, but the break statement provides an explicit exit when the user inputs "stop".

9. When to use Break?

  • Normal Condition: Use when you know exactly when the loop should end (e.g., based on a counter or a clear status flag that changes predictably).
  • Break Statement: Use when the exit condition depends on something unpredictable, like user input, finding a specific item, or a complex internal check. It's often used with while True loops to create an "indefinite" loop that runs until a specific internal event triggers the exit.

10. Can you find the error?

# Goal: Print 10 to 1
num = 10
while num > 0:
    print(num)
    num = num + 1

Answer: C. It is an infinite loop (numbers keep getting larger!).

Explanation: The goal is to print from 10 down to 1, but num is being incremented (num = num + 1). Since num starts at 10 and keeps increasing (11, 12, 13...), it will always be greater than 0, making the condition num > 0 perpetually True.

11. Guess the Number Game (Python Code Example)

This game uses a while True loop and a break statement.

Requirements:

  • Set a secret_number = 7.
  • Use while True: to keep asking for a guess.
  • If the guess is correct, use break and print "You Win!".
  • Else, print "Try again!".
# Secret Number Guessing Game
secret_number = 7

while True:
    guess = int(input("Guess the secret number: "))

    if guess == secret_number:
        print("You Win!")
        break  # Exit the loop if guess is correct
    else:
        print("Try again!")

12. Key Takeaways

  • A while loop runs as long as the condition is True.
  • Always update your control variable to avoid infinite loops.
  • Use break to exit a loop manually from the inside.
  • Python uses indentation to define what's inside the loop.

Test Your Knowledge

Challenge yourself with targeted practice questions and accelerate your mastery of While Loops & Control Flow.

Practice CBT Study Flashcards