smartyfy.mrindigi.com

Python Master Course V2 — 026. Continue and Pass Statements

SMARTYFY ACADEMY · MODULE 03 · LESSON 026 OF 200

Continue and Pass Statements

Estimated study: 60–90 minutes · Prerequisite: Lesson 025 and preceding Python foundations.

Skip an iteration with continue and distinguish pass as a placeholder.

Video lesson

Video not available yet. This position is reserved for a verified lesson video link or player. The written lesson can be completed without it.

Learning outcomes

  • Explain skip an iteration with continue and distinguish pass as a placeholder.
  • Trace program state and predict the output.
  • Recognize common errors and boundary conditions.
  • Apply the concept to a complete practical project.
  • Write independent tests and justify results.

Understand the technique

Skip the remaining work for one item

continue skips the remaining statements in the current loop body. A for loop then requests its next item; a while loop returns to its condition. The loop itself is still active. Use continue when a record is intentionally excluded from the current calculation, especially when handling that exclusion early makes the normal processing path easier to read.

By contrast, pass is a statement that does nothing. Python still executes the statements after it. It is useful as a temporary placeholder where the grammar requires a statement, such as a not-yet-implemented function body. It does not skip a record, stop a loop, validate data, or suppress an exception.

Compare the same loop with one statement changed

print("Continue version")
for number in [1, 2, 3]:
    if number == 2:
        continue
    print(number)

print("Pass version")
for number in [1, 2, 3]:
    if number == 2:
        pass
    print(number)

Expected output:

Continue version
1
3
Pass version
1
2
3

In the first loop, the condition for 2 leads straight to the next iteration, bypassing print. In the second loop, pass performs no action and execution reaches print anyway. Indentation matters: the print is outside the if but inside the loop in both versions. Neither statement has the same effect as break, which would prevent later items from being processed.

Guided task: total only accepted measurements

For this classroom dataset, values are integers and the policy is to include only positive measurements. Zero means “no usable measurement”; negatives are excluded. Count exclusions as well as adding accepted values so that missing contributions are visible in the final report. Exclusion here is a stated data rule, not a substitute for validating arbitrary types.

values = [10, -2, 5, 0, 3]
total = 0
excluded = 0
for value in values:
    if value <= 0:
        excluded += 1
        continue
    total += value
print("Total:", total)
print("Excluded:", excluded)

Expected output:

Total: 18
Excluded: 2

Ten is added. Negative two increments excluded and skips the addition. Five is added, zero is excluded, and three is added. Updating the exclusion count before continue is essential: an update after it would be unreachable. For an empty list, both totals remain zero because their initialization happens before the loop.

Keep while-loop updates on every required path

A for loop advances its iterator automatically. A while loop often relies on an explicit update, so continue can accidentally bypass that update. In the following safe version, the counter changes before a value is skipped.

number = 0
while number < 5:
    number += 1
    if number % 2 == 0:
        continue
    print(number)

Expected output:

1
3
5

If the update were placed after continue, an even counter could remain unchanged forever. Trace the skipped path separately from the accepted path and ask whether both can reach a false condition. Stop an accidental endless program using the editor’s Stop control or Ctrl+C in its terminal before repairing it.

Use placeholders deliberately

A comment alone cannot fill a required function body; pass can. A function containing only pass implicitly returns None when called. Mark such scaffolding as unfinished rather than presenting it as a working implementation. For completed code, choose an explicit conditional structure that states the real behavior. Continue can reduce deep indentation, but a simple positive condition is often equally clear when only one short operation is involved.

Runnable example and expected output

Setup: Python 3.10 or newer, standard library only. Save the following as lesson_026.py and run python lesson_026.py (or python3).

for n in range(1,6):
    if n%2==0:
        continue
    print(n)

Expected output:

1
3
5

Walkthrough: Identify the initial variable values, follow the control flow in execution order, and write down every printed result. Change one input, predict the new output and then run the modified program.

Guided real-world project

This project applies continue and pass statements to a practical scenario. Review the input values and decision or iteration rule before running the program.

def sum_positive(values):
    total=0
    for value in values:
        if value<=0:
            continue
        total+=value
    return total
print(sum_positive([10,-2,5,0,3]))

Expected output:

18

Testing plan: Run the shown sample, add an empty or minimum-size input where applicable, and test a value at the relevant boundary. For larger systems, separate the core calculation from user input so it can be tested independently.

Dataset contract: this example accepts a list of integer measurements. Positive values contribute to the total; zero and negative values are intentionally excluded. This exclusion rule does not validate arbitrary input types.

Common mistakes and professional practices

  • Confusing an expression’s value with a side effect.
  • Skipping validation of inputs and collection sizes.
  • Misreading the order of operations or changes to state.
  • Forgetting to test zero, empty, minimum and maximum cases.
  • Using overly complicated logic instead of descriptive intermediate variables.

Debugging approach: Print the relevant state, compare each step with the expected result, isolate the first divergence, correct the underlying rule, and rerun all cases.

Think, trace, and solve

Attempt each question before revealing its answer. Explain your reasoning as well as the final result.

1. Follow the skipped path

for value in [0, 2, -1, 4]:
    if value <= 0:
        continue
    print(value * 2)

Predict all output.

Optional hint

Trace which values reach the print after continue.

Reveal answer and reasoning

Expected output:

4
8

Zero and negative one trigger continue before printing. The accepted values 2 and 4 are doubled.

2. Replace continue with pass

for value in [1, 2, 3]:
    if value == 2:
        pass
    print(value)

Does 2 print? Explain the control flow.

Optional hint

Pass performs no jump; follow the statement after the if.

Reveal answer and reasoning

Expected output:

1
2
3

Yes. Pass does nothing; it does not jump anywhere. Every iteration reaches the print statement.

3. Repair a while-loop trap

Reading fragment: trace this broken loop; do not run it.

number = 0
while number < 3:
    if number == 0:
        continue
    number += 1

Why does this loop fail to finish? Repair it so it advances through 1, 2, and 3 and prints only 2 and 3.

Optional hint

An update must occur on the skipped path as well as the accepted path.

Reveal answer and reasoning
number = 0
while number < 3:
    number += 1
    if number == 1:
        continue
    print(number)

Expected output:

2
3

The original repeatedly skips the update while number is zero. The repaired version increments before its skip decision, so every iteration makes progress.

4. Check an all-excluded dataset

For the measurement task, what are total and excluded after values = [0, -4, -1]? How does this differ from empty input?

Optional hint

Count supplied records separately from their contribution to the total.

Reveal answer and reasoning

Total is 0 and excluded is 3. Each value hits the exclusion branch, and no addition occurs. Empty input leaves total at 0 and excluded at 0. Reporting the count distinguishes “nothing was supplied” from “everything supplied was excluded”.

5. Understand a placeholder function

def calculate_discount():
    pass

print(calculate_discount())

What prints, and why would treating this as a working discount calculation be a mistake?

Optional hint

A function that reaches its end without return has an implicit result.

Reveal answer and reasoning

Expected output:

None

The function reaches its end without an explicit return, so it returns None. Pass only makes the unfinished body syntactically valid. It does not compute a zero discount or implement the intended rule.

Mastery checkpoint

Before advancing, explain the main concept without notes, predict the example output, run the project, and create at least three independent tests. If your results differ, revisit the debugging section.

Summary: Skip an iteration with continue and distinguish pass as a placeholder. Reliable programs combine clear logic, appropriate validation and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.