Python while Loop
Table of Contents + −
In the last lesson you learned the for Loop. It runs through a list of things one by one. That works great when you know how many times you want to repeat. But what about when you do not know? Think of asking someone for a password until they get it right. You have no idea if they will need one try or ten. That is where the while loop comes in.
🤔 Why do we need a while loop?
Picture this. You are building a login screen. You want to keep asking for the password until the person types the correct one. With a for loop you would have to guess a number. Ask three times? Five times? But people are unpredictable. Some get it on the first go. Some take a while.
The pain is simple. You need to repeat something. But you do not know how many times.
The fix is the while loop. It does not count. It just keeps going as long as a condition stays true. The moment that condition becomes false, it stops.
🧩 What is a while loop?
A while loop repeats a block of code over and over. But it only repeats while a condition is true.
Think of a kettle. It keeps heating while the water is not yet boiling. Once the water boils, the condition “not boiling” becomes false. So it stops. The kettle does not count how many seconds it ran. It just checks one thing again and again. Are we there yet?
That is exactly how a while loop thinks. Before each round it asks one question. If the answer is yes, it runs the code and asks again. If the answer is no, it walks away.
🧱 The syntax
Here is the basic shape of a while loop.
while condition: # code that runs each time the condition is true passHere is what each piece does.
whileis the keyword that starts the loop.conditionis a question that gives backTrueorFalse. The loop runs while this condition isTrue.- The colon
:ends the line, just like withifandfor. - The indented block below is the code that repeats. Everything indented runs each round.
The loop checks the condition first. Then it runs the body. So if the condition is false right from the start, the body never runs at all.
🔢 A simple counter example
The clearest way to feel a while loop is to count. Here we print the numbers 1 through 5.
This code starts a counter at 1 and keeps printing while it stays at 5 or below.
count = 1
while count <= 5: print(count) count = count + 1
print("Done!")Now let me walk through what happens, line by line.
- We set
countto1before the loop. This is our starting point. - The loop checks. Is
countless than or equal to5? Yes,1is. So it runs the body. - Inside, it prints
count. Then it adds1to it. Nowcountis2. - It goes back up and checks again.
2is still<= 5, so it repeats. - This keeps going until
countbecomes6. Now6 <= 5is false, so the loop stops. - After the loop ends, we print
"Done!".
Here is exactly what this prints.
Output
1 2 3 4 5 Done!
The most important line here is count = count + 1. That single line is what moves us toward the finish. Without it, count would stay 1 forever and the loop would never stop. More on that danger in a second.
🔁 You must change something inside the loop
This is the one idea that trips up most people. So let me say it plainly. A while loop only stops when its condition becomes false. So something inside the loop must change to make that happen.
In the counter example, that something was count = count + 1. Each round nudged count closer to the value that ends the loop.
A while loop usually has three moving parts.
| Part | What it does | In our example |
|---|---|---|
| Setup | Create the variable before the loop | count = 1 |
| Condition | The question checked each round | count <= 5 |
| Update | The change that moves toward stopping | count = count + 1 |
Miss the update, and your loop runs forever. Let me show you what that looks like and why it matters.
⚠️ The infinite loop
An infinite loop is a loop that never stops, because its condition never becomes false. This is the classic while loop bug. Everyone writes one sooner or later.
Look at this code. Can you spot the problem?
count = 1
while count <= 5: print(count) # oops, we forgot to change countHere count starts at 1 and stays 1. The condition count <= 5 is true on the first round. And it is still true on every round after, because nothing ever changes count. So Python prints 1 again and again and again, without end. Your screen fills up and the program never reaches anything below the loop.
Caution
If your program seems frozen or keeps printing the same thing forever, you are probably stuck in an infinite loop. To stop it, click on the terminal and press Ctrl+C (hold the Control key and tap C). This tells Python to interrupt the program right away.
Infinite loops are not always a mistake, though. Sometimes you want a loop to run “forever” until something special happens inside it. We will see exactly that pattern next.
💬 A real example: keep asking until they type “quit”
Now for something closer to real life. Let us write a tiny program that keeps reading what the person types. It only stops when they type quit.
This code reads input in a loop and breaks out of it the moment the word quit arrives.
command = ""
while command != "quit": command = input("Type a command (or 'quit' to stop): ") print(f"You typed: {command}")
print("Goodbye!")Here is the walkthrough.
- We start
commandas an empty string"". We need it to exist before the loop checks it. - The condition is
command != "quit". That means “command is not equal to quit”. So the loop runs as long as the person has not typedquit. - Inside,
input()asks them to type something and stores it incommand. This is the line that changes our variable each round. - We print what they typed.
- The loop goes back and checks the condition again with the new value of
command. - The moment they type
quit, the condition becomes false, the loop ends, and we print"Goodbye!".
If someone runs this and types hello, then python, then quit, the program prints this.
Output
Type a command (or ‘quit’ to stop): hello You typed: hello Type a command (or ‘quit’ to stop): python You typed: python Type a command (or ‘quit’ to stop): quit You typed: quit Goodbye!
Notice that input() is doing the job that count = count + 1 did earlier. It is the thing that changes each round. That gives the loop a way to eventually stop.
⚠️ Common Mistakes
A few traps catch almost everyone when they start with while loops. Watch for these.
- Forgetting to update the variable. This is the big one. If nothing in the body changes the condition, you get an infinite loop.
# ❌ Avoid: count never changes, runs forevercount = 1while count <= 5: print(count)
# ✅ Good: count grows each round, so the loop endscount = 1while count <= 5: print(count) count = count + 1- Using the variable before creating it. The condition is checked before the first round, so the variable must already exist.
# ❌ Avoid: 'total' does not exist yet when the loop checks itwhile total < 100: total = total + 10
# ✅ Good: create it firsttotal = 0while total < 100: total = total + 10- Mixing up the comparison. Writing
count < 5when you meantcount <= 5will stop one round too early. Read your condition slowly and ask “does this include the last value I want?”.
✅ Best Practices
Keep these small habits and your while loops will stay friendly.
- Set up your variable before the loop, on its own line, so the starting value is easy to see.
- Make sure the body clearly changes something that the condition depends on. If you cannot point to that line, you have a problem.
- Prefer a
forloop when you already know how many times to repeat. Reach forwhilewhen the number of repeats is unknown, like reading input. - When you do want a loop that runs until a special event,
while True:paired with abreakis a clean pattern. You will meetbreakin the next lesson.
🧩 What You’ve Learned
You now know how to repeat code when you do not know the count up front.
- ✅ A
whileloop repeats its body as long as the condition staysTrue. - ✅ The condition is checked before each round, so it can run zero times.
- ✅ Something inside the loop must change, or you get an infinite loop that never stops.
- ✅ An infinite loop can be stopped with Ctrl+C in the terminal.
- ✅
whileshines when the number of repeats is unknown, like asking until someone typesquit.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
When does a while loop keep running?
Why: A while loop runs its body over and over for as long as its condition stays True.
- 2
What usually causes an infinite loop?
Why: If no line in the body changes what the condition depends on, the condition never turns False and the loop never stops.
- 3
How do you stop a program stuck in an infinite loop in the terminal?
Why: Ctrl+C interrupts the running program and breaks you out of the infinite loop.
- 4
In `while command != "quit":`, when does the loop stop?
Why: The condition is true while command is not quit, so it becomes false (and the loop ends) once the person types quit.
🚀 What’s Next?
You can repeat code now. But sometimes you want to jump out of a loop early, the instant something happens. That is the job of one small but mighty keyword.