Kahibaro
Discord Login Register

7.3 while loops

Understanding `while` Loops in Python

A while loop repeats a block of code as long as a condition is True.

The general form is:

while condition:
    # code to repeat
    # (also called the loop body)

Basic `while` Loop Example

count = 1
while count <= 5:
    print("Count is:", count)
    count = count + 1
print("Loop finished!")

What happens step-by-step:

  1. Start: count = 1
  2. Check: count <= 51 <= 5True → run the body
  3. Print, then update: count becomes 2
  4. Check again: 2 <= 5 → still True → run again
    ...
  5. When count becomes 6: 6 <= 5False → loop ends

Key idea: Something inside the loop must change so that the condition eventually becomes False.

The Importance of Updating the Condition

If you forget to update the variable used in the condition, the loop may never stop.

Example: Infinite Loop (what *not* to do)

number = 1
while number <= 5:
    print(number)
    # Oops! We forgot: number = number + 1

Here, number is always 1, so number <= 5 is always True.
The loop runs forever (until you manually stop it).

Always check:

  1. Is my condition correct?
  2. Am I changing the variables used in the condition inside the loop?

`while` Loops and User Input

while loops are very useful when you don’t know in advance how many times you need to repeat something, especially with user input.

Repeating Until the User Types “quit”

command = ""
while command != "quit":
    command = input("Enter a command (or 'quit' to stop): ")
    print("You typed:", command)
print("Program ended.")

Validating User Input

You can use while to keep asking the user until they give a valid answer.

age = int(input("Enter your age (1-120): "))
while age < 1 or age > 120:
    print("That doesn't look right.")
    age = int(input("Please enter an age between 1 and 120: "))
print("Thanks! Your age is", age)

The loop repeats only when the age is outside the allowed range.

Counting Up and Counting Down

while loops often use a counter variable that you increase or decrease each time.

Counting Up

i = 1
while i <= 3:
    print("i is", i)
    i = i + 1

Output:

i is 1
i is 2
i is 3

Counting Down

i = 3
while i > 0:
    print("i is", i)
    i = i - 1
print("Blast off!")

Output:

i is 3
i is 2
i is 1
Blast off!

Using `while` for Simple Games and Repeated Tasks

Because while loops can run an unknown number of times, they are perfect for:

Example: Guessing Until Correct

secret = 7
guess = int(input("Guess the number: "))
while guess != secret:
    print("Wrong, try again!")
    guess = int(input("Guess the number: "))
print("Correct! The secret number was", secret)

The loop only ends when guess == secret.

`while True` Loops

Sometimes you want a loop that runs “forever” until you manually break out of it from inside.

This is often written as:

while True:
    # do something
    # maybe break at some point

Example: menu that exits when the user chooses 4:

while True:
    print("Menu:")
    print("1. Say hello")
    print("2. Say goodbye")
    print("3. Do nothing")
    print("4. Exit")
    choice = input("Choose an option (1-4): ")
    if choice == "1":
        print("Hello!")
    elif choice == "2":
        print("Goodbye!")
    elif choice == "3":
        print("...")
    elif choice == "4":
        print("Exiting...")
        break   # leave the loop
    else:
        print("Invalid choice. Try again.")

Here:

(The details of break and continue are covered in their own section; here you just see how break can stop a while loop.)

Common `while` Loop Patterns

1. Loop Until a Certain Count

count = 0
while count < 10:
    print("Count is", count)
    count = count + 1

2. Loop Until a Condition Becomes False

battery = 100
while battery > 0:
    print("Battery at", battery, "%")
    battery = battery - 10
print("Battery empty!")

3. Loop Until a “Sentinel” Value

A sentinel is a special value that means “stop now”.

total = 0
print("Enter numbers to add. Enter 0 to finish.")
number = int(input("Number: "))
while number != 0:
    total = total + number
    number = int(input("Number: "))
print("Total is", total)

Here, 0 is the sentinel value that stops the loop.

Typical Mistakes with `while` Loops

1. Forgetting to Update the Variable

x = 0
while x < 5:
    print(x)
    # missing: x = x + 1  → infinite loop

Always ensure the loop body moves you toward the condition becoming False.

2. Using `==` Instead of `=`

Inside the loop, you usually want = when you change a variable:

# Wrong:
x == x + 1   # This compares instead of updates
# Right:
x = x + 1

3. Condition That Is Never True or Never False

Examples:

# Never runs (x starts at 10, but you check for x < 5)
x = 10
while x < 5:
    print(x)
    x = x + 1
# Never stops (condition always true)
y = 1
while y > 0:
    print(y)
    y = y + 1

When debugging, print the variables used in the condition to see how they change.

When to Use a `while` Loop

Use a while loop when:

In later sections you will compare while loops to for loops and see when each is more convenient.

Views: 71

Comments

Please login to add a comment.

Don't have an account? Register now!