Courseiva
PCEP-30-02Chapter 8 of 16Objective 3.3

While Loops and Loop Control

Exam objective 3.3 asks you to write while loops and control loops using break, continue, and else. This is a major building block for PCEP-30-02 because loops let you repeat actions without writing the same code over and over — a skill you will use constantly in Python.

12 min read
Intermediate
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture While Loops and Loop Control

The Washing Machine Cycle Analogy

Have you ever started a washing machine and then stood there, watching it, waiting for it to finish so you could hang the clothes out?

That exact moment is a perfect picture of a 'while loop'. The machine runs its cycle (the loop continues) while the tub is still turning. At the start, you check a condition: 'Is the cycle still running?' As long as the answer is yes, the machine keeps spinning, draining, and rinsing (repeating the loop body). The moment the cycle finishes, the condition becomes false, and the machine stops — it moves on to the beep. But what if you need to pause the machine halfway to add a forgotten sock? That is 'break'. You interrupt the normal flow early. What if the machine detects a fabric that doesn't need the full spin cycle? It might 'continue' by skipping the remainder of the current rinse and jumping straight to the next step. Finally, the machine has an 'else' clause: once the cycle ends naturally (without a break), it might unlock the door and let you know it's done. If you force-stopped it early with a break, that else clause never runs. This maps directly to code: while condition: do something. Use 'break' to exit instantly, 'continue' to skip the rest of the current loop iteration, and 'else' to run code only if the loop finished without break.

How It Actually Works

A while loop is a structure in Python that lets you repeat a block of code as long as a certain condition remains true. Think of it as a repeating 'if' statement: while the condition is true, do this. When the condition becomes false, the loop stops and the program moves on. This is fundamentally different from a 'for loop', which runs a fixed number of times or over a known sequence of items. A while loop runs an unknown number of times, until something changes.

Here is the basic syntax:

while condition: # code to repeat

For example:

x = 0 while x < 5: print(x) x = x + 1

This will print 0, 1, 2, 3, 4. Each time the loop runs, it checks if x is still less than 5. Inside the loop, we add 1 to x. Eventually, x becomes 5, the condition 'x < 5' becomes false, and the loop stops.

If you forget to update the variable inside the loop — for example, if you forget the line 'x = x + 1' — the condition never becomes false. The loop runs forever. This is called an 'infinite loop'. Your program will hang, and you will have to interrupt it. This is a very common beginner mistake.

Now, what if you want to stop a while loop early, before the condition becomes false? That is where 'break' comes in. The 'break' keyword immediately exits the loop, regardless of the condition. For example:

x = 0 while True: if x == 3: break print(x) x = x + 1

Here, the loop condition is 'True', which is always true — so this would normally run forever. But when x reaches 3, the 'break' command fires, and the loop ends. The output is 0, 1, 2.

What if you want to skip the rest of the current run (iteration) of the loop, but keep looping? That is 'continue'. When Python hits 'continue', it immediately jumps back to the top of the loop to check the condition again, ignoring any lines after 'continue' in the current iteration. For example:

x = 0 while x < 6: x = x + 1 if x == 3: continue print(x)

This prints 1, 2, 4, 5, 6. When x is 3, the 'continue' fires, so the print statement is skipped for that iteration. The loop then moves to x = 4 and continues normally.

Finally, Python while loops can have an 'else' clause. This is a block of code that runs once the loop condition becomes false — but only if the loop was not exited by a 'break'. If you use 'break' to exit, the 'else' block is skipped. For example:

x = 0 while x < 3: print(x) x = x + 1 else: print('Loop finished normally')

This prints 0, 1, 2, and then 'Loop finished normally'. Now add a break:

x = 0 while x < 3: if x == 2: break print(x) x = x + 1 else: print('Loop finished normally')

This prints 0, 1, and then stops. It never prints 'Loop finished normally' because the loop was exited by 'break', not by the condition becoming false.

Why do these tools exist? Without 'break' and 'continue', you would have to write complicated nested if statements to handle special cases inside loops. The 'else' clause on a while loop is a Python-specific feature that many other languages do not have. It is useful for running cleanup code that should only execute if the loop completed successfully — for example, searching a list and reporting 'found' or 'not found'.

Flowchart showing the decision points in a while loop: condition check, loop body execution, break/continue paths, and the else clause.

Walk-Through

1

Initialise a loop variable

Before the while loop, you must create a variable that will be used in the condition. For example, 'count = 0'. If you do not initialise it, Python will raise a NameError when it checks the condition.

2

Write the while keyword and condition

Type 'while' followed by a condition that evaluates to True or False. The condition typically compares a variable to a value, like 'count < 5'. Python evaluates this condition before each iteration.

3

Add the colon and indent the loop body

After the condition, put a colon. The next lines must be indented (usually 4 spaces). These indented lines are the loop body — they will repeat as long as the condition is True.

4

Write the logic inside the loop body

Inside the body, write the operations you want to repeat. Crucially, include a line that changes the loop variable (e.g., 'count = count + 1') so the condition eventually becomes False. If you forget, the loop will run forever.

5

Use break or continue as needed

If you need to exit early despite the condition still being True, use 'break'. If you need to skip the rest of the current iteration and jump back to the condition check, use 'continue'. Place these inside conditional if statements to control exactly when they fire.

6

Add an else clause (optional)

After the loop body, you can unindent and write 'else:' followed by an indented block. This block runs only if the loop ended because the condition became False, not because you used 'break'.

What This Looks Like on the Job

Imagine you are a junior IT support technician at a company that manages user accounts. You have a list of employee IDs in a file, and you need to check each ID against a central authorisation server to see if the account is still active. The server can be slow, and sometimes it returns an error.

You write a Python script that reads the IDs one by one. For each ID, you open a connection to the server. But you cannot be sure how many times you will need to retry if the server is down. This is a classic case for a while loop: you loop while the server has not responded correctly. You set a counter for retries. The code might look like this:

retries = 0 max_retries = 5 while retries < max_retries: response = query_server(employee_id) if response == 'OK': print('Account active') break else: print('Server error, retrying...') retries = retries + 1 else: print('Failed after maximum retries. Logging issue.')

Here, the while loop runs as long as retries is less than max_retries. Inside, we try to contact the server. If we get a good response, we break out immediately. If not, we increment retries and try again. If the loop ends because retries reached the maximum (without a break), the else clause fires, alerting us to log a ticket.

Another real-world scenario: a batch processing script that processes orders. The script polls a database for new orders. While there are orders pending, it processes them one by one. If an order has invalid data, the script might use 'continue' to skip that order and move to the next, rather than crashing the whole batch. For example:

while orders_remaining(): order = get_next_order() if not validate(order): log_invalid(order) continue process_payment(order) ship_order(order)

Without 'continue', you would have to wrap the payment and shipping steps inside an if statement, which is less readable.

In IT, you also use while loops for input validation. Suppose you ask a user to enter a number between 1 and 10. You can keep asking while the input is invalid:

user_input = '' while not user_input.isdigit() or int(user_input) not in range(1, 11): user_input = input('Enter a number from 1 to 10: ') print('Thank you.')

This loop will continue until the user gives a digit between 1 and 10. The moment they do, the condition becomes false and the loop ends.

These are everyday tasks for a programmer: retrying operations, skipping bad data, and repeating actions until a condition is met.

How PCEP-30-02 Actually Tests This

PCEP-30-02 tests three specific skills with while loops: knowing the syntax, understanding the flow of control with break/continue/else, and predicting the output of a given loop. The exam does not ask you to write long programs — it gives you short code snippets and asks what they print, or whether they will run without error.

Key topics the exam loves:

Basic while loop syntax. You must know that the condition is tested before each iteration. If the condition is false at the start, the loop body never executes at all.

The 'break' keyword. A common trap: they give you a while True loop with a break inside. You need to trace exactly when the break fires. If the break is inside an if statement that never becomes true, the loop runs forever. Expect a question like: 'What is the output?' with a while True loop that has no break. The answer is: infinite loop (or nothing, because the program hangs).

The 'continue' keyword. They love to put a continue right before a variable update. If you skip the update, the condition never changes, and the loop becomes infinite. For example:

x = 0 while x < 5: if x == 2: continue x = x + 1

This is an infinite loop, because when x is 2, continue jumps to the top without incrementing x, so x stays 2 forever. The exam expects you to spot this. - The 'else' clause. You must memorise: else runs when the loop condition becomes false, but NOT when the loop is terminated by break. They will test this with a break inside a conditional. For example: 'How many times does the print statement execute?'

- Nested loops. While loops can be inside other while loops. The exam may ask about the total number of iterations or what 'break' does to a nested loop (it breaks only the innermost loop). - The condition must be an expression that evaluates to a boolean (True or False). Any non-zero number, non-empty string, or non-empty list is treated as True. Zero, empty string, and empty list are treated as False. For example, 'while 1:' runs forever because 1 is truthy. - Common traps to memorise: * Forgetting to initialise the loop variable. If you try to check 'while x < 5:' without x being defined, you get a NameError. * Off-by-one errors. If you start at 0 and want 5 iterations, you use 'while x < 5', not 'while x <= 5'. * Infinite loops caused by incorrect increment or missing increment. - The exam expects you to know that 'else' is part of the while loop syntax, not an if statement. They might show you code with else indented at the same level as while, and ask you to identify what it does.

To prepare: practise tracing short while loops on paper. Write down the value of each variable at every step. This is exactly what the exam does.

Key Takeaways

A while loop repeats a block of code as long as its condition evaluates to True; if the condition is False initially, the body never runs.

The 'break' keyword instantly exits the innermost enclosing loop, regardless of the loop's condition.

The 'continue' keyword skips the rest of the current loop iteration and jumps back to check the condition for the next iteration.

An 'else' clause on a while loop executes only if the loop terminated normally (condition became False), not if it was terminated by a 'break'.

Forgetting to update the loop variable inside a while loop will almost certainly cause an infinite loop.

The condition in a while loop is tested at the start of each iteration, not at the end, so a loop can execute zero times.

Using 'while True:' creates an infinite loop unless there is a 'break' statement inside to exit it.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

While Loop

Runs while a condition is true, so the number of iterations may be unknown

Condition checked at the start of each iteration

Often used when the number of repetitions depends on user input or external data

For Loop

Iterates over a fixed sequence (list, string, range)

Number of iterations is known before the loop starts

Often used when you know exactly how many items to process

break

Exits the loop immediately

Skips the rest of the current iteration only

The loop does not repeat after break — it stops entirely

continue

Jumps back to the top to check the condition

Does not exit the loop; the next iteration still runs if condition is true

Useful for skipping specific items in a sequence

Loop with else

Has an extra block that runs if loop ends normally

Useful for 'not found' detection after searching

Can replace a flag variable

Loop without else

No else block

Must use a separate variable to track if a break occurred

More common in other programming languages

Watch Out for These

Mistake

The else block on a while loop runs when the loop condition is true.

Correct

The else block runs only when the loop condition becomes false naturally — not when the loop is exited by break.

This is a confusing name. People associate 'else' with 'if else', where it runs when the if condition is false. Here, else has a very different behaviour.

Mistake

Using continue inside a while loop will skip the next iteration entirely.

Correct

Continue skips only the remaining code in the current iteration and jumps back to check the condition. It does not skip the next iteration — the next iteration still happens if the condition is true.

Beginners think 'continue' means 'skip the next round', analogous to 'continue to the next item'. The correct mental model is 'skip the rest of this round'.

Mistake

A while loop's condition is checked at the end of each iteration.

Correct

The condition is checked at the beginning of each iteration, before the loop body runs. If the condition is false at the start, the body never runs.

This is the opposite of a do-while loop in some other languages, which many beginners have heard of even if they haven't used it.

Mistake

You can use break and continue only inside while loops, not inside if statements within the loop.

Correct

Break and continue are valid inside if statements as long as those if statements are inside a while (or for) loop. The break/continue applies to the enclosing loop, not the if.

Beginners see 'break' inside an if and think it breaks the if statement, not the loop. They misunderstand the scope of the control keyword.

Mistake

A while loop with condition 'while False:' will run once because the condition is tested after the first execution.

Correct

A while loop with a condition that is initially False will never run the loop body. The condition is tested before the first iteration.

This is a straight syntax misunderstanding. Some beginners guess that the loop runs at least once, like a do-while pattern they may have glimpsed.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between a while loop and a for loop?

A for loop iterates over a known sequence (like a list or a range of numbers), running a fixed number of times. A while loop runs as long as a condition is true, which may be an unknown number of times.

Can a while loop run forever?

Yes, if the condition never becomes false. For example, 'while True:' or if you forget to update a variable inside the loop. An infinite loop will cause your program to hang and you must interrupt it with Ctrl+C.

Does the else clause on a while loop always run?

No. The else clause runs only if the loop condition becomes false naturally. If you exit the loop with a break, the else clause is skipped.

Is a while loop slower than a for loop?

Not significantly in most cases. The performance difference is negligible for typical PCEP-level tasks. The choice between them should be based on what you need to iterate over, not speed.

What happens if I use break inside a nested while loop?

Break only exits the innermost loop it is inside. If you have two while loops one inside the other, a break inside the inner loop will only stop the inner loop; the outer loop continues running.

Can I use continue to go back to the start of the loop without checking the condition?

No. Continue skips the rest of the current iteration and jumps to the top, where Python immediately checks the condition again. If the condition is false, the loop ends even if there are more iterations planned.

Terms Worth Knowing

Keep going

You've finished While Loops and Loop Control. Continue through the PCEP-30-02 study guide to build a complete picture of the exam.

Done with this chapter?