South Plantation High School logo
South Plantation High School · Procedural Programming with Python

while Loops & the pass Instruction

Counting loops · Accumulators · Infinite loops · pass · Lesson review

Review the lesson slides, then complete the assignment at the bottom of this page. Your assignment work is saved in this browser on this computer. When you check a task, your name, period, and which tasks are complete are shared with your teacher (your code is not). When you finish, print it or save it as a PDF to turn in.
1 / 17
Lesson Review

while Loops & pass

whilecount += 1pass

Teaching your program to repeat itself.

By the end of this lesson you will be able to:

  • Explain what a loop is and why programmers use them.
  • Write a while loop with a condition, a colon, and an indented body.
  • Build a counting loop with its three parts: start, condition, and update.
  • Use a loop to add up numbers and to keep asking the user until they get it right.
  • Spot and fix infinite loops and off-by-one mistakes.
  • Use the pass instruction as a placeholder.
How to use this page: Use Next and Back (or the arrow keys). In a TRY IT editor, click ▶ Run to watch the whole loop, or Step to go one line at a time. The Variables box shows how each value changes as the loop runs.

Words you will hear today

WordWhat it means
loopA block of code that repeats
iterationOne trip through the loop body
loop variableThe variable the condition checks, like count
updateThe line that changes the loop variable so the loop can end
accumulatorA variable that collects a running total
infinite loopA loop whose condition never becomes False
placeholderSomething that holds a spot for code you will write later (pass)
  • A loop repeats a block of code.
  • A while loop repeats as long as its condition is True.
  • Iteration, loop variable, update, accumulator, infinite loop.

Up to now, every line of our programs ran once, or was skipped by an if statement. Today we learn to repeat code. A loop lets one block of code run again and again, as many times as we need. We will also meet pass, the instruction that does nothing on purpose.

The Big Idea

Why do we need loops?

Without a loop: copy and paste
print(1)
print(2)
print(3)
print(4)
print(5)

That works for 5 numbers. What about 500? Or "keep asking until the password is right"? You cannot know ahead of time how many times to copy the line.

With a loop: write it once
count = 1
while count <= 5:
    print(count)
    count = count + 1
1 2 3 4 5

To print 500 numbers, change just one value: 5 becomes 500.

Real life loops: a game keeps running while you have lives left. A music app keeps playing while there are songs in the playlist. A login page keeps asking while the password is wrong.

Loops follow the DRY rule

Programmers have a saying: Don't Repeat Yourself (DRY). Copied lines are a problem because if you need to change them (say, print a label before each number), you have to change every copy and hope you did not miss one. With a loop, you change one line.

Two kinds of repeating

  • A known number of times: print 1 to 500, roll a die 10 times.
  • Until something happens: until the password is right, until the player runs out of lives.

A while loop can do both, which is why we learn it first.

  • Loops repeat code without copying it.
  • Each time through the loop is called an iteration.
  • DRY: Don't Repeat Yourself.

Imagine your teacher asks you to print the numbers 1 to 500. Nobody wants to type 500 print statements. A loop lets us write the instruction once and tell Python how long to keep repeating it. Each time the loop body runs is called one iteration.

while Loops

Anatomy of a while loop

whilekeyword
count <= 5condition
:colon
····4 spaces
print(count)indented body
  • It looks like an if statement, with one big difference: after the body runs, Python goes back up and checks the condition again.
  • If the condition is still True, the body runs again.
  • When the condition becomes False, Python skips the body and continues with the first line after the loop.
Think of it this way: if asks the question once. while keeps asking the question until the answer is no.
While loop flowchart Python checks the condition. If True, it runs the body and then goes back to check the condition again. If False, it leaves the loop and runs the code after the loop. Before the loop Is the condition True? True Run the body go back False After the loop

if vs. while with the same condition

count = 1
if count <= 5:
    print(count)      # prints 1, one time
count = 1
while count <= 5:
    print(count)      # prints 1, 2, 3, 4, 5
    count += 1

The only real difference is what happens after the body. An if moves on. A while jumps back to the top and asks again.

The loop must change something. If nothing in the body can ever make the condition False, the loop will repeat forever.

  • while, condition, colon, indented body.
  • After the body, Python checks the condition again.
  • The loop ends when the condition is False.
  • if moves on after the body; while jumps back and asks again.

A while loop has the same four parts as an if statement. The difference is the arrow that goes back up in the flowchart. After the body finishes, Python returns to the condition and asks again. It only leaves the loop when the answer is False.

while Loops

Try it: watch a loop run

Click Step a few times to move one line at a time, or click ▶ Run to watch it all. Keep an eye on the Variables box: count goes up by 1 each time through the loop.

rannever ran
Notice: line 2 is checked 6 times, not 5. The 6th time, count is 6, so 6 <= 5 is False, and Python jumps to line 5.

The full trace

Check #countcount <= 5What happens
11Trueprints 1, count becomes 2
22Trueprints 2, count becomes 3
33Trueprints 3, count becomes 4
44Trueprints 4, count becomes 5
55Trueprints 5, count becomes 6
66Falseloop ends, prints Done!

After the loop, count is 6, not 5. The variable keeps its last value. The loop stopped because count went one past the limit.

  • The condition is checked before every iteration, plus one last time when it becomes False.
  • Line 5 is outside the loop, so it runs once at the end.
  • After the loop, count holds the first value that failed the condition.

Let's step through this together. Watch line 2 every time. It is checked, it is True, the body runs, and then we come back to line 2. Count how many times line 2 turns green. It is 6 times, because Python needs one more check to find out the loop is done.

while Loops

The three parts of a counting loop

count = 1                # 1. START
while count <= 5:        # 2. CONDITION
    print(count)
    count = count + 1    # 3. UPDATE
PartWhat it does
1. StartCreate the loop variable before the loop. Python needs it to check the condition the first time.
2. ConditionDecides whether to run the body again. When it is False, the loop ends.
3. UpdateChanges the loop variable inside the body, so the condition will eventually become False.

The short way to update

You already know the short-form operators. They are perfect for loops:

Long formShort form
count = count + 1count += 1
count = count - 1count -= 1
count = count + 2count += 2
total = total + numtotal += num
Forget the start? Python shows NameError: name 'count' is not defined. Forget the update? The loop never ends. More on that in a few slides.

Where each part must go

  • Start: above the while line, at the same indentation as the while. If it were inside the body, it would reset every iteration and the loop would never end.
  • Condition: on the while line itself.
  • Update: inside the body, indented. Usually it is the last line of the body.
Start inside the loop = infinite loop: if count = 1 were moved inside the body, every iteration would set it back to 1, then add 1 to make 2, then reset to 1 again... The condition would always be True.
  • Start before the loop, condition on the while line, update inside the body.
  • count += 1 means count = count + 1.
  • Start above the loop, update inside it.

Almost every counting loop has these three parts. Point to each one: start, condition, update. If you are missing any of them, the loop either crashes or never stops. When you write a loop, check for all three before you run it.

while Loops

Try it: change the start, stop, and step

Change the three values and run the loop. Try these: start 2, stop 10, step 2 (even numbers). Start 5, stop 50, step 5 (count by fives). Start 1, stop 3, step 1.

Challenge: before you click Run, predict the last number printed. Then check yourself. With start 1, stop 10, step 3, is the last number 10?

Finding the last number without running

List the values: start, start + step, start + 2×step, and so on. Stop at the last one that still makes the condition True.

With start 1, stop 10, step 3: 1, 4, 7, 10. 10 <= 10 is True, so 10 is printed. The next value, 13, fails. So yes, the last number is 10.

With start 1, stop 9, step 3: 1, 4, 7. The next value, 10, is already past 9, so 7 is last. The stop value is a limit, not a promise: it only prints if the counting happens to land on it.

  • The step is how much the loop variable changes each time.
  • The last number printed is the last value that still makes the condition True.
  • The stop is a limit; it prints only if the counting lands on it.

Here you control all three parts. Make a prediction before each run. With a step of 3 starting at 1, the numbers are 1, 4, 7, 10. Now try stop 9. The last number becomes 7, because 10 is not less than or equal to 9.

while Loops

Counting down

A loop can count down just as easily. Three things flip:

  • Start high: n = 10
  • Condition checks the low end: while n > 0:
  • Update subtracts: n -= 1
Careful: if you count down but write n += 1 by mistake, n keeps growing and n > 0 is always True. That loop never ends!

Check that the update moves toward the end

For every loop, ask: "Does the update move the variable toward making the condition False?"

ConditionNeeds the variable to...Update
n <= 10grow past 10n += 1
n > 0shrink to 0n -= 1
lives > 0shrink to 0lives -= 1 when the player gets hit

Countdown trace from 3: prints 3, 2, 1, then n becomes 0, 0 > 0 is False, and Liftoff! prints. 0 itself is never printed.

  • Counting down: start high, check the low end, subtract.
  • The update must move the variable toward making the condition False.
  • The update must move toward making the condition False.

Rocket launches count down, so let's count down. The update has to move the value in the direction that will eventually make the condition False. If we count down with plus equals, the number grows forever and the loop never stops.

while Loops

Adding up numbers with a loop

An accumulator is a variable that collects a running total. It starts at 0 before the loop, and each iteration adds to it.

  • total = 0 starts the running total.
  • total += num adds the current number.
  • num += 1 moves on to the next number.

Change limit and watch total grow in the Variables box. With limit 4: 0 + 1 + 2 + 3 + 4 = 10.

Why start at 0? Adding 0 does not change a sum, so 0 is the perfect starting point. If you forget total = 0, the line total += num causes NameError: name 'total' is not defined.

Trace with limit = 4

numnum <= 4total after total += num
1True1
2True3
3True6
4True10
5False(loop ends, prints Sum: 10)

Two variables, two jobs: num controls how long the loop runs. total stores the answer. Mixing them up (like total += 1) is a common mistake.

Other things you can accumulate: multiply (start at 1, not 0, since anything times 0 is 0), or build a string (start at "" and use +=).

  • Accumulator: start at 0, add inside the loop.
  • The loop variable and the accumulator are two different variables.
  • Sums start at 0; products start at 1; strings start at "".

This loop uses two variables. num counts 1, 2, 3, 4, and total keeps a running sum. Step through slowly and say the total out loud after each iteration: 1, 3, 6, 10. Accumulators show up everywhere: game scores, shopping cart totals, and grade averages.

while Loops

Keep asking until it is right

A while loop is perfect when you do not know how many times something will repeat. A password check keeps asking while the guess is wrong.

  • Ask once before the loop, so guess exists for the first check.
  • Ask again at the end of the body. That new answer is the update.
  • When the guess matches, guess != secret is False and the loop ends.

In the box, type what the user enters, separated by commas. Try java, Python, python. Why is Python rejected?

Why ask twice?

The first input() (before the loop) gives guess a value so the while line can check it. The second input() (at the end of the body) is the update: it gets a new guess, so the condition can eventually become False. Without it, the same wrong guess would be checked forever.

The same pattern checks for valid numbers

age = int(input("Age (1-120): "))
while age < 1 or age > 120:
    print("That is not a real age.")
    age = int(input("Age (1-120): "))

This is called input validation: keep asking until the answer makes sense.

  • Use while when the number of repeats depends on the user.
  • Get input before the loop and again at the end of the body.
  • String comparisons are case sensitive.
  • The second input() is the update.
  • Input validation: keep asking until the answer makes sense.

This kind of loop does not count at all. It repeats until the user gets it right, which could be the first try or the tenth. The second input at the bottom of the body is the update. Without it, the user would never get another chance, and the loop would run forever.

Debugging

Infinite loops

An infinite loop never ends, because its condition never becomes False. The most common cause is a missing update.

This loop is missing count += 1. Run it and see what happens. Then check the box to add the update and run it again.

How to stop a runaway loop: press Ctrl + C in the terminal (or click the stop button in your editor). Python stops and shows KeyboardInterrupt. This is not a bug in Python. It just means you stopped the program.

Other causes

  • The update moves the wrong way (n += 1 while counting down).
  • The update is not indented, so it is outside the loop and never runs during the loop.
  • The condition can never be False, like while True: with nothing to stop it.

Three-question check for any loop

  1. Is there an update? Something in the body must change the loop variable.
  2. Is the update inside the body? It must be indented with the other body lines.
  3. Does it move the right way? Up for </<= conditions, down for >/>=.
Intentional "forever" loops: games often use while True: on purpose and leave the loop with the break keyword when the player quits. You will see break later. Without a break, while True: never ends.
  • Infinite loop = the condition never becomes False.
  • Check: is there an update, is it indented, and does it move the right way?
  • Ctrl + C stops a running program.
  • Is there an update, is it indented, does it move the right way?

Every programmer writes an infinite loop sooner or later. It is not dangerous. The program just keeps going. When it happens, press Control C to stop it, then look for the update. Nine times out of ten it is missing, indented wrong, or going the wrong direction.

Debugging

Off-by-one: < vs <=

An off-by-one mistake makes a loop run one time too many or one time too few. It usually comes from picking the wrong comparison operator.

ConditionPrintsIterations
while count < 5:1 2 3 44
while count <= 5:1 2 3 4 55

Switch the operator in the editor and compare the output and the loop counter.

Tip: to print 1 to 5, read the condition out loud: "while count is less than or equal to 5." If the last number should be included, you need <=.

Two ways to write the same loop

while count <= 5: and while count < 6: do exactly the same thing with whole numbers. Pick the one that matches how you think about the problem. "Up to and including 5" reads best as <= 5.

Test the edges

After writing a loop, check just two values: the first thing printed and the last thing printed. Off-by-one mistakes almost always show up at one of those two ends. The demo prints the final value of count to help you see where it stopped.

  • < stops before the number. <= includes it.
  • Always check the first and last values printed.
  • Check the first and last values the loop prints.

Off by one is a classic bug. The program runs without errors, but it gives you four numbers instead of five. Test it: switch between less than and less than or equal to, and look at the last number printed each time.

Debugging

A loop that never runs

The condition is checked before the first iteration. If it is already False, the body is skipped completely, zero times.

With x = 10, the condition x < 5 is False right away, so only the line after the loop runs. Change x to 2 and run it again.

Zero iterations is not an error. Python does not warn you. If a loop seems to do nothing, check the starting value against the condition.

Zero times can be correct

A loop that runs zero times is sometimes exactly right. If a player already has 0 lives, the game loop should not run. If the user types the right password the first time, the "try again" message should never print.

It is only a bug when you expected the loop to run. If a loop seems to do nothing, print the starting value just before the loop and check it against the condition by hand.

  • A while loop can run zero times.
  • The condition is checked first, before the body ever runs.
  • Zero iterations is sometimes correct, e.g. the right password first try.

A while loop checks first and runs second. If the very first check is False, the body never runs at all. That is sometimes exactly what you want, and sometimes a bug caused by a bad starting value.

The pass Instruction

pass: the instruction that does nothing

Every if, elif, else, and while must have at least one indented statement in its body. Sometimes you are not ready to write that code yet.

pass is a statement that does nothing at all. It fills the empty spot so Python can run the rest of your program.

Empty body: Python will not run it
score = 95
if score >= 90:
    # TODO: add a prize later
print("Report done.")
IndentationError: expected an indented block after 'if' statement on line 2
With pass: Python runs it
score = 95
if score >= 90:
    pass   # TODO: add a prize later
print("Report done.")
Report done.
A comment is not enough. Python ignores comments, so a body with only a comment counts as empty. pass is a real statement, so it counts.
  • pass is lowercase and goes on its own line, indented like any other body line.
  • It does not stop a loop, skip anything, or print anything. It just takes up the spot.

Why Python needs pass

In Python, a colon at the end of a line promises "an indented block comes next." Python uses that block to know where the if or loop ends. An empty block would break that rule, so Python needs something there. pass is the smallest possible statement: it keeps the promise and does nothing else.

Not the same as a comment: a comment is removed before Python even looks at the structure. pass is a real instruction that Python runs (and it does nothing).

  • pass does nothing. It is a placeholder.
  • A body with only a comment causes an IndentationError.
  • A colon promises a block; pass keeps the promise.

Pass is the strangest instruction in Python, because its whole job is to do nothing. Why would we want that? Because Python refuses to run a program with an empty body, even if we put a comment there. Pass holds the spot until we are ready to write the real code.

The pass Instruction

Using pass as a placeholder

Programmers use pass while planning a program. Write the structure first, test it, then fill in the details.

Run this with a score of 95, then 70. When the score is 90 or higher, the pass line runs, but nothing happens, and the program keeps going.

Careful with loops: a loop whose body is only pass never updates anything. If its condition starts True, it is an infinite loop!
lives = 3
while lives > 0:
    pass    # TODO: write the game here
# This never ends: lives is always 3

Planning with pass

Many programmers write the skeleton of a program first: all the decisions and loops, with pass in each body. They run it to check that there are no syntax errors, then fill in one body at a time and test each part as they go.

choice = input("Menu (play/help/quit): ")
if choice == "play":
    pass   # TODO: start the game
elif choice == "help":
    pass   # TODO: show the rules
else:
    print("Goodbye!")

Labeling each pass with a # TODO comment reminds you what still needs to be written.

  • Use pass to sketch out a program before filling it in.
  • Replace each pass with real code when you are ready.
  • A while body of only pass is usually an infinite loop.
  • Write the skeleton with pass, then fill in one part at a time.

Watch the pass line turn green when the score is 95. Python really does run it, and it really does nothing. In a loop, pass is risky: nothing in the body changes the loop variable, so the condition never changes either.

Debugging

Common mistakes

MistakeWrong codeWhat happensFix
No update in the bodywhile count <= 5:
    print(count)
No error. Infinite loop. Ctrl + C shows KeyboardInterruptAdd count += 1 inside the body
Missing colonwhile count < 3SyntaxError: expected ':'while count < 3:
Body not indentedwhile count < 3:
print(count)
IndentationError: expected an indented block after 'while' statement on line 2Indent the body 4 spaces
Body is only a commentwhile count < 3:
    # later
IndentationError: expected an indented block after 'while' statement on line 2Use pass
Capital letterWhile count < 3:SyntaxError: invalid syntaxwhile is lowercase
= instead of ==while count = 3:SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?while count == 3: (or a different operator)
No start valuewhile total < 10: with no total = ... before itNameError: name 'total' is not definedCreate the variable before the loop
Update has extra spaces     n += 1 (5 spaces)IndentationError: unexpected indentLine it up with the rest of the body
Wrong operatorwhile count < 5: to print 1 to 5No error. Off by one: prints 1 to 4while count <= 5:

Error messages shown are from Python 3.13. Older versions word some messages a little differently. Notice that the most common loop mistakes give no error message, so always check your output.

Sort the mistake by what you see

  • The program never starts (SyntaxError / IndentationError): look at the while line (lowercase? colon? == not =?) and the indentation of the body.
  • The program never stops: infinite loop. Use the three-question check: update present, indented, right direction.
  • It runs but the numbers are a little off: off-by-one. Check < vs. <= and the start value.
  • NameError: a variable used in the condition was never created before the loop.
  • Syntax and indentation errors stop the program before it starts.
  • Infinite loops and off-by-one mistakes run, but give the wrong result.
  • Never starts: syntax. Never stops: update. Slightly off: < vs <=.

Look at how many of these mistakes give no error at all. The infinite loop and the off by one are the two you will see most. Your best tool for catching them is tracing: write down the value of the loop variable after every iteration, just like the Variables box does.

Practice

Check yourself

Predict the answer, then click Check. This is practice only. Nothing is graded or recorded.

Use a trace table for every question: make columns for each variable and the condition. Write a new row for each check of the condition. When the condition is False, the loop is over. Count the rows where it was True: that is the number of iterations.
  • Trace the loop variable on paper: write its value after every iteration.
  • Check the condition one last time to see when the loop stops.

Use a trace table for these: make a column for each variable and write down the values after each iteration. That is exactly what the Variables box was doing for you in the Try It editors.

Summary

Cheat sheet

Counting loop

count = 1
while count <= 5:
    print(count)
    count += 1

Start, condition, update. Use <= to include the last number.

Repeat until right

guess = input("Password: ")
while guess != "python":
    print("Try again.")
    guess = input("Password: ")
print("Welcome!")

Ask before the loop and again at the end of the body.

pass

if score >= 90:
    pass   # TODO
else:
    print("Keep going!")

Does nothing. Holds the spot for code you will write later.

Before you run a loop, check:

  • The loop variable is created before the loop
  • The while line is lowercase and ends with a colon :
  • The body is indented 4 spaces, including the update
  • The update moves the variable toward making the condition False
  • You picked the right operator (< or <=) for the last value
  • Any empty body has pass in it, not just a comment

Key words to know

while loop · iteration · start / condition / update · accumulator · infinite loop · KeyboardInterrupt (Ctrl + C) · off-by-one error · input validation · pass · trace table

  • while repeats while the condition is True.
  • Start, condition, update. pass is a placeholder.
  • Know the key words: iteration, accumulator, infinite loop, off-by-one, pass.

Let's wrap up. A while loop repeats as long as its condition is True. Counting loops need a start, a condition, and an update. Loops can also repeat until the user gets it right. And pass is the placeholder that lets you leave a body empty for now. Run through this checklist before you run any loop.