Introduction to Python Programming

Andrew J. Pounds, Ph.D.

πŸ”„ Exercise Five: The While Loop

Executing a block of code over and over until a certain condition is met is one of the things that makes computer programming much easier than spreadsheeting for certain problems. The simplest, and most general form of this type of procedure, called a loop, is implemented in Python with the while statement.

What You'll Learn:
  • How to repeat code using while loops
  • How to control when a loop stops
  • How to avoid infinite loops
  • Common loop patterns and practical examples
πŸ’‘ Why Are Loops Important?

Imagine you need to add up 1000 numbers, or print a message 50 times, or keep asking a user for input until they type "quit." Without loops, you'd have to write the same code over and over. Loops let you write it once and repeat it as many times as needed!

πŸ” 1. The while Construct

The while statement will look a lot like the if statementβ€”it has a Boolean argument. The difference is that the while loop will keep executing the indented code inside until the Boolean statement becomes false.

Basic Structure

while condition:
    # This indented code runs repeatedly
    # as long as condition is True
    # Don't forget to update variables!

Your First While Loop

A = 0
while A < 5:
    print(A)
    A += 1
0
1
2
3
4

How Does This Work?

Let's trace through the loop step by step:

1 A = 0 β€” Variable A is initialized to 0
2 A < 5? Is 0 < 5? Yes (True) β€” Enter the loop
3 print(A) β€” Prints 0
4 A += 1 β€” A becomes 1
5 Go back to the while and check again: Is 1 < 5? Yes β€” Continue...
... This repeats until A becomes 5
βœ“ When A = 5: Is 5 < 5? No (False) β€” Exit the loop

Iteration Table

Here's what happens during each iteration:

Iteration Value of A (start) Is A < 5? Output Value of A (end)
1 0 True 0 1
2 1 True 1 2
3 2 True 2 3
4 3 True 3 4
5 4 True 4 5
6 5 False β€” Loop exits
πŸ“ Remember: Indentation Matters!

Just like with if statements, the code inside a while loop must be indented. Python uses indentation to know which lines belong inside the loop. When you stop indenting, you're outside the loop.

βš–οΈ 2. while vs if: What's the Difference?

Both while and if use Boolean conditions, but they behave very differently:

Feature if Statement while Loop
Execution Runs the code block once (if condition is true) Runs the code block repeatedly (while condition is true)
Checking Checks condition once Checks condition before each iteration
Use Case Make a decision Repeat an action

Side-by-Side Example

Using if (runs once):
x = 1
if x < 5:
    print(x)
    x += 1
print("Done")
1
Done
Using while (repeats):
x = 1
while x < 5:
    print(x)
    x += 1
print("Done")
1
2
3
4
Done

♾️ 3. Infinite Loops

Intentional Infinite Loops

If you want the loop to run forever (called an infinite loop), you could just write:

while True:
    print("Help me -- I can't stop!")
⚠️ Warning: This loop will never stop on its own! The condition True is always true, so Python will keep printing the message forever. You would need to manually stop the program (usually by pressing Ctrl+C or clicking the stop button in your IDE).

While intentional infinite loops have their uses (like game loops or servers that run continuously), most of the time you'll want your loops to eventually stop.

Unintentional Infinite Loops

Unintended infinite loops are common errors that new programmers often face. While they can generally be traced back to a logic error, the most common cause is that the programmer, in the indented sections of code, does not update variables used in the Boolean expression that controls whether or not the loop is executed.

🚨 Danger: Forgetting to Update the Loop Variable

Imagine what would happen if there were no A += 1 in our first loop:

# THIS IS BROKEN - DO NOT RUN!
A = 0
while A < 5:
    print(A)
    # Oops! We forgot A += 1
    # A will ALWAYS be 0
    # 0 < 5 will ALWAYS be True
    # This prints 0 forever!

Since A never changes, the condition A < 5 is always True, and the loop runs forever!

How to Stop a Runaway Program

If you accidentally create an infinite loop:

  • In Spyder: Click the red square (stop) button or press Ctrl+C
  • In the terminal: Press Ctrl+C
  • In IDLE: Go to Shell β†’ Restart Shell

πŸ“ 4. Common While Loop Patterns

Pattern 1: Counting Up

# Count from 1 to 5
count = 1
while count <= 5:
    print(count)
    count += 1
1
2
3
4
5

Pattern 2: Counting Down

# Countdown from 5 to 1
count = 5
while count >= 1:
    print(count)
    count -= 1
print("Blastoff!")
5
4
3
2
1
Blastoff!

Pattern 3: Accumulator (Running Total)

# Sum the numbers 1 through 5
total = 0
number = 1

while number <= 5:
    total = total + number
    print("Adding " + str(number) + ", total is now " + str(total))
    number += 1

print("Final sum: " + str(total))
Adding 1, total is now 1
Adding 2, total is now 3
Adding 3, total is now 6
Adding 4, total is now 10
Adding 5, total is now 15
Final sum: 15

Pattern 4: User-Controlled Loop (Sentinel Value)

Keep asking for input until the user types a specific value to quit:

# Keep asking until user types "quit"
user_input = ""

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

print("Goodbye!")
Enter a command (or 'quit' to exit): hello
You entered: hello
Enter a command (or 'quit' to exit): test
You entered: test
Enter a command (or 'quit' to exit): quit
Goodbye!

Pattern 5: Input Validation

Keep asking until the user provides valid input:

# Keep asking until user enters a positive number
number = -1

while number < 0:
    number = int(input("Enter a positive number: "))
    if number < 0:
        print("That's not positive! Try again.")

print("Thank you! You entered: " + str(number))
Enter a positive number: -5
That's not positive! Try again.
Enter a positive number: -2
That's not positive! Try again.
Enter a positive number: 7
Thank you! You entered: 7

🎯 5. Complete Examples

Example 1: Guessing Game

# Number guessing game
secret_number = 7
guess = 0
attempts = 0

print("=== Guess the Number ===")
print("I'm thinking of a number between 1 and 10")
print()

while guess != secret_number:
    guess = int(input("Enter your guess: "))
    attempts += 1
    
    if guess < secret_number:
        print("Too low! Try again.")
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print("Correct!")

print()
print("You got it in " + str(attempts) + " attempts!")
=== Guess the Number ===
I'm thinking of a number between 1 and 10

Enter your guess: 5
Too low! Try again.
Enter your guess: 8
Too high! Try again.
Enter your guess: 7
Correct!

You got it in 3 attempts!

Example 2: Calculate Average

# Calculate average of numbers entered by user
print("=== Average Calculator ===")
print("Enter numbers to average. Type -1 to finish.")
print()

total = 0
count = 0
number = 0

while number != -1:
    number = float(input("Enter a number (-1 to finish): "))
    if number != -1:
        total = total + number
        count = count + 1

print()
if count > 0:
    average = total / count
    print("You entered " + str(count) + " numbers")
    print("The sum is: " + str(total))
    print("The average is: " + str(average))
else:
    print("No numbers were entered.")
=== Average Calculator ===
Enter numbers to average. Type -1 to finish.

Enter a number (-1 to finish): 10
Enter a number (-1 to finish): 20
Enter a number (-1 to finish): 30
Enter a number (-1 to finish): -1

You entered 3 numbers
The sum is: 60.0
The average is: 20.0

Example 3: Multiplication Table

# Print multiplication table for a number
number = int(input("Enter a number for the multiplication table: "))

print()
print("=== Multiplication Table for " + str(number) + " ===")
print()

multiplier = 1
while multiplier <= 10:
    result = number * multiplier
    print(str(number) + " x " + str(multiplier) + " = " + str(result))
    multiplier += 1
Enter a number for the multiplication table: 7

=== Multiplication Table for 7 ===

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

⚠️ Common Mistakes (And How to Fix Them)

Mistake 1: Forgetting to Update the Loop Variable

❌ Wrong (Infinite Loop!):
count = 1
while count <= 5:
    print(count)
    # Forgot to increment count!
βœ… Correct:
count = 1
while count <= 5:
    print(count)
    count += 1  # Don't forget this!

Mistake 2: Wrong Initial Value

❌ Wrong (Loop never runs!):
count = 10  # Starting too high!
while count < 5:
    print(count)
    count += 1
# 10 < 5 is False, so loop body never executes
βœ… Correct:
count = 1  # Start at appropriate value
while count < 5:
    print(count)
    count += 1

Mistake 3: Off-by-One Errors

❌ Wrong (Prints 1-4 instead of 1-5):
count = 1
while count < 5:  # Should be <= 5
    print(count)
    count += 1
βœ… Correct:
count = 1
while count <= 5:  # Use <= to include 5
    print(count)
    count += 1

Mistake 4: Updating Variable Outside the Loop

❌ Wrong (Infinite Loop!):
count = 1
while count <= 5:
    print(count)
count += 1  # This is OUTSIDE the loop (not indented!)
βœ… Correct:
count = 1
while count <= 5:
    print(count)
    count += 1  # This is INSIDE the loop (indented)

Mistake 5: Forgetting the Colon

❌ Wrong:
count = 1
while count <= 5  # ERROR! Missing colon
    print(count)
    count += 1
βœ… Correct:
count = 1
while count <= 5:  # Don't forget the colon!
    print(count)
    count += 1

πŸ’ͺ Practice Exercises

Try writing these programs on your own!

Exercise 1: Print Even Numbers

Write a program that prints all even numbers from 2 to 20.

Expected output: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20

Hint: Start at 2 and add 2 each time, OR start at 1 and use an if statement to check if the number is even.

Exercise 2: Sum of Numbers

Write a program that:

  1. Asks the user for a positive integer N
  2. Calculates the sum of all integers from 1 to N
  3. Displays the result

Example: If N = 5, output should be 15 (because 1+2+3+4+5 = 15)

Exercise 3: Factorial Calculator

Write a program that calculates the factorial of a number:

  1. Asks the user for a non-negative integer
  2. Calculates N! (N factorial = N Γ— (N-1) Γ— (N-2) Γ— ... Γ— 1)
  3. Displays the result

Example: 5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1 = 120

Exercise 4: Password Checker

Write a program that:

  1. Has a secret password stored in a variable
  2. Keeps asking the user to enter the password
  3. Gives them a maximum of 3 attempts
  4. Prints "Access granted!" if correct, or "Account locked!" after 3 failed attempts

Exercise 5: Powers of Two

Write a program that prints all powers of 2 that are less than 1000:

Expected output: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512

Hint: Start with 1 and keep multiplying by 2.

Exercise 6: Number Reverser

Write a program that reverses a positive integer:

  1. Asks for a positive integer
  2. Reverses its digits
  3. Displays the reversed number

Example: Input: 12345 β†’ Output: 54321

Hint: Use % 10 to get the last digit, and // 10 to remove it.

πŸ“‹ Quick Reference

Basic While Loop Structure

variable = initial_value

while condition:
    # Code to repeat
    # ...
    # Update the variable!
    variable = new_value

Common Loop Patterns

Count up:
i = 1
while i <= n:
    # do something
    i += 1
Count down:
i = n
while i >= 1:
    # do something
    i -= 1
Accumulator:
total = 0
while condition:
    total += value
Sentinel value:
x = ""
while x != "quit":
    x = input("...")

Checklist: Avoiding Infinite Loops

  • βœ“ Is the loop variable initialized before the loop?
  • βœ“ Is the loop variable updated inside the loop?
  • βœ“ Will the update eventually make the condition false?
  • βœ“ Is the update statement properly indented (inside the loop)?

⭐ Key Takeaways

  • βœ“ The while loop repeats code as long as a condition is True
  • βœ“ The condition is checked before each iteration
  • βœ“ If the condition is False initially, the loop body never runs
  • βœ“ Always update the loop variable inside the loop to avoid infinite loops
  • βœ“ Make sure the update is indented so it's inside the loop
  • βœ“ Don't forget the colon (:) after the while condition
  • βœ“ while True: creates an infinite loop (usually intentional)
  • βœ“ Use Ctrl+C to stop a runaway program

❓ Need Help?

If your program doesn't work, check these common issues:

  1. Program runs foreverβ€”Are you updating the loop variable? Is the update indented correctly?
  2. Loop never runsβ€”Is your initial value correct? Is your condition correct?
  3. Off by oneβ€”Check whether you need < or <= (same for >)
  4. SyntaxErrorβ€”Did you forget the colon after while?
  5. IndentationErrorβ€”Is all your loop code properly indented?
πŸ’‘ Debugging Tip: Add print() statements inside your loop to see what's happening:
count = 1
while count <= 5:
    print("DEBUG: count =", count)  # See the value each time
    # ... rest of your code
    count += 1
Remember: Loops are one of the most powerful tools in programming! They let you automate repetitive tasks and process large amounts of data. Take time to understand how the condition and the update work together, and always trace through your loop manually for the first few iterations to make sure it does what you expect.