while LoopsGet Certified
What Is a while Loop?
A while loop repeats a block of code as long as a condition remains true. Unlike a for loop, which is designed to iterate a known number of times, a while loop is ideal when you do not know in advance how many times the loop should run.
This makes while loops especially useful when a program needs to respond to changing values or wait for a particular condition to be met. For example, a program can continue processing data until a limit is reached or a user provides a specific response. Python checks the condition before executing the loop body, so the result of that check determines whether another iteration takes place.
The general form is:
while condition:
# indented block
# that runs while the condition is True
- The condition is checked before each iteration.
- If the condition is already false, the loop body never runs.
- Something inside the loop (or the condition itself) must eventually make the condition false, otherwise the loop becomes infinite.
- In this browser environment, keep loops small (usually under 20–30 iterations) so the page stays responsive.
Basic while Loop
The classic pattern uses a counter that is updated inside the loop until it reaches a limit.
A counter-controlled while loop is one of the easiest ways to understand how repeated execution works. You first assign a starting value to a variable, then use a comparison to decide whether the next iteration should run. After each pass, update the counter so that the loop gradually moves toward its stopping condition.
This pattern is useful for tasks such as displaying a sequence of numbers, processing a fixed number of records, or calculating a running result. The following examples demonstrate how a counter can control both simple repetition and mathematical calculations.
Try It: Simple Counting Loop
This loop prints the numbers 1 through 5. Notice that the counter is increased on every pass so the condition eventually becomes false.
count = 1
while count <= 5:
print("Count is", count)
count = count + 1
print("Loop finished.")count and sets it to 1. This is the starting value for the loop.count <= 5 is tested before every iteration. While it is true, the indented block runs.count by 1. Without this line the condition would never become false and the loop would run forever.while, so it runs only after the loop ends.Try It: Summing Numbers
A common use of a while loop is to accumulate a total until a limit is reached.
total = 0
number = 1
while number <= 10:
total = total + number
print("Added", number, "→ running total =", total)
number = number + 1
print("Final sum from 1 to 10 is", total)total to 0 so we can add values into it.number at 1.number is 10 or less (only 10 iterations).Countdown with a while Loop
While loops are also useful for counting down.
Instead of increasing a value, you can decrease it during each iteration to create a countdown. This approach is useful for situations where a process needs to move toward a lower limit, such as displaying remaining attempts or counting down to the start of an activity. The loop continues while the current value satisfies the specified condition.
Remember to choose a condition that matches the direction in which the counter is moving. When the counter decreases, a condition such as n > 0 can keep the loop running until the value reaches zero. The next example demonstrates this pattern.
Try It: Simple Countdown
This example counts down from 5 to 1 and then prints a message. Only five iterations occur.
n = 5
while n > 0:
print(n)
n = n - 1
print("Lift off!")n is still greater than 0.Sentinel-Controlled Loops
A sentinel is a special value that signals the end of input. The loop keeps reading until the user enters that value.
Sentinel-controlled loops are useful when the program cannot predict how many values a user will provide. Instead of asking for a fixed number of entries, the program checks each new value for a designated stopping signal. This allows users to decide when they have finished entering information.
The sentinel value is used to control the loop rather than as part of the actual data being processed. For example, entering 0 can tell a program to stop collecting numbers while the other entered values are added together. Make sure the program reads the first value before the loop and requests another value during each iteration.
Try It: Read Numbers Until Zero
The Program Input box already contains several numbers ending with 0. The loop stops when it sees the sentinel 0. Only a few numbers are processed.
total = 0
number = int(input("Enter a number (0 to stop): "))
while number != 0:
total = total + number
number = int(input("Enter a number (0 to stop): "))
print("Sum of the numbers is", total)Input Validation with while
While loops are excellent for forcing the user to enter a valid value before continuing.
Programs often need to check user input before using it in calculations or other operations. A while loop makes this possible by repeatedly evaluating whether the entered value meets the required rules. If the value is invalid, the program can display a helpful message and request another entry.
This technique is commonly used for checking positive numbers, menu selections, age limits, and other required input. You can also combine multiple conditions to control how long the program keeps asking. Adding an attempt limit makes the process more predictable and prevents repeated invalid entries from keeping the loop running indefinitely.
Try It: Ask Until a Positive Number Is Given
The loop keeps asking until the user types a number greater than zero. A safety counter prevents an endless series of bad inputs in this browser environment.
attempts = 0
max_attempts = 5
number = -1
while number <= 0 and attempts < max_attempts:
number = int(input("Enter a positive number: "))
attempts = attempts + 1
if number <= 0:
print("That is not positive. Try again.")
if number > 0:
print("Thank you! You entered", number)
else:
print("Too many invalid attempts.")Using break and continue
Although there is a dedicated lesson on break and continue, they are frequently used inside while loops. Here is a short, safe illustration.
Sometimes a loop needs to change its normal flow before its condition becomes false. Python provides break and continue for handling these situations. Both statements affect the current iteration, but they serve different purposes depending on what the program needs to do.
Use break when a particular result means that no further repetition is necessary. Use continue when you want to skip the remaining statements in the current iteration and move to the next condition check. Understanding the difference helps you write loops that respond more clearly to special cases.
Try It: Stop Early with break
The loop would normally run up to 10 times, but it stops as soon as it finds a number divisible by 7.
break.n = 1
while n <= 10:
if n % 7 == 0:
print(n, "is divisible by 7. Stopping.")
break
print(n, "is not divisible by 7.")
n = n + 1
print("Done searching.")break immediately leaves the loop.break.Try It: Skip with continue
This loop prints only the odd numbers from 1 to 8. Even numbers are skipped with continue.
n = 0
while n < 8:
n = n + 1
if n % 2 == 0:
continue
print(n, "is odd")n at the beginning of the body so that continue does not create an infinite loop.continue jumps back to the top of the loop, skipping the print statement.Nested while Loops (Small Scale)
A while loop can contain another while loop. Keep both the outer and inner limits very small in this environment.
Nested while loops are useful when a task involves repeating one process inside another. The outer loop usually controls a larger operation, while the inner loop handles repeated work for each outer iteration. For example, you can use this structure to generate rows and columns, process a small grid, or display multiplication tables.
Each loop needs its own controlling variable and stopping condition. The inner counter is generally initialized again whenever the outer loop starts a new iteration, allowing the inner loop to complete its task each time. Carefully updating both counters prevents unexpected repetition and makes the execution easier to follow.
Try It: Tiny Multiplication Table
This produces a compact 1-to-3 multiplication table. Both loops are limited to three iterations each.
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, "×", j, "=", i * j, end=" ")
j = j + 1
print() # new line after each row
i = i + 1end=" " keeps everything on one line.Avoiding Infinite and Excessively Long Loops
Because this tutorial runs inside the browser, a loop that never ends or that performs millions of iterations will freeze the page. Follow these rules:
An infinite loop occurs when the condition remains true and the program has no reachable way to exit. This can happen when a counter is not updated, when the wrong comparison is used, or when a variable changes in an unexpected direction. Even a loop that eventually ends can cause performance problems if it performs too many iterations.
Before running a while loop, check how its controlling variables change and estimate how many times the body will execute. For programs that depend on user input or other uncertain conditions, include an additional stopping mechanism such as an attempt counter. These simple precautions make your code easier to test and help keep browser-based Python execution responsive.
- Always change a variable that appears in the condition, or provide a clear
break. - Prefer a modest upper bound (for example
while n <= 20) rather than an open-endedwhile True. - When reading user input, add a maximum number of attempts.
- Never write a loop whose number of iterations depends on a huge range or an unknown external event without a safety limit.
- If you are experimenting and the page becomes unresponsive, simply reload the page.
while versus for
Both while and for loops are used to repeat instructions, but they are suited to different situations. A for loop is generally more convenient when working through a known sequence or a defined number of iterations. A while loop is more flexible when repetition depends on a condition that may change while the program is running.
For example, displaying every item in a list is usually straightforward with a for loop, whereas repeatedly asking for input until the user enters a valid value is a natural use of a while loop. Choosing the appropriate loop makes your program easier to understand and maintain. Consider whether you are processing a known collection of items or waiting for a condition to change before deciding which structure to use.
- Use a
forloop when you know the sequence or the number of iterations in advance (lists,range(), etc.). - Use a
whileloop when the end condition depends on data that is discovered during the loop (user input, searching until a match, etc.). - Many counting tasks can be written with either construct; choose the one that makes the intention clearest.
Key Takeaways
Python while loops provide a flexible way to repeat instructions whenever a condition needs to remain true. They are particularly useful for counting, processing user input, validating values, and repeating operations until a specific result is reached. Understanding how the condition is evaluated and how variables change during each iteration is essential for writing reliable loops.
As you practice, pay attention to the difference between normal loop termination and early exits using control statements. Also, make sure that every loop has a clear stopping mechanism, especially when its behavior depends on user input. The following points summarize the most important concepts covered in this lesson.
- A
whileloop repeats its body as long as its condition stays true. - The condition is tested before every iteration; if it is false at the start, the body never runs.
- Something inside the loop must make the condition false, otherwise the loop is infinite.
- Sentinel values and input-validation patterns are natural uses of while loops.
breakleaves the loop immediately;continueskips the rest of the current iteration.- In the browser, keep the number of iterations small and always include a safety limit when the end condition is not obvious.
Frequently Asked Questions
Here are answers to common questions about Python while loops, including how they behave, when to use them, and how to prevent problems during execution. These explanations reinforce the concepts introduced in the examples and help clarify situations you may encounter when writing your own programs.
If you are unsure why a loop is not stopping or how to choose between different loop structures, review the relevant answers below. You can also experiment with the examples in this lesson to see how changing a condition or updating a variable affects the program's behavior.
What is the difference between a while loop and a for loop?
A for loop is designed to iterate over a known sequence or a fixed number of times (for example using range()). A while loop continues as long as a condition remains true and is therefore better when you do not know in advance how many iterations will be needed.
How can I avoid an infinite while loop?
Make sure that every path through the loop body changes at least one variable that is used in the condition, or that a break statement can eventually be reached. Adding a maximum-iteration counter is a good safety measure, especially in interactive programs.
What happens if the condition is false when the loop starts?
The loop body is skipped entirely and execution continues with the first statement after the loop. This is normal and useful; it means the loop is only entered when there is work to do.
Can a while loop contain another while loop?
Yes. Nested while loops are allowed. Keep both the outer and inner limits small in this browser environment so the page does not freeze.
When should I use break inside a while loop?
Use break when you have found what you were searching for, or when an error or special condition makes further iterations unnecessary. It provides an immediate exit from the loop.
Is while True ever acceptable?
Yes, when the loop is intended to run until an explicit break occurs (for example a menu that keeps showing options until the user chooses “quit”). Always make sure the break condition is reachable and, in teaching examples, prefer a clear upper bound.
Why do the examples use such small numbers?
This tutorial runs Python inside the browser. Very long loops or infinite loops can freeze the tab. The examples therefore stay under a few dozen iterations so you can experiment safely.
How do I repeat a block until the user enters a valid value?
Initialize a variable to an invalid value, then use a while loop whose condition checks that the value is still invalid. Inside the loop read a new value. Add a maximum number of attempts so the loop cannot run forever.