Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 06 / VALUES AND CONTROL FLOW

Decisions that read like decisions

Use branching to make business rules explicit and testable.

FoundationTutorial 9 min core+6 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 9 minutes; optional deep dive: 6 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Write if/elif/else
  • Order overlapping rules
  • Use guards instead of deep nesting
01

Only the first matching branch runs

An if/elif/else chain chooses the first branch whose condition is true, or the else branch when none is true.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

When several categories overlap, such as score thresholds, branch order decides which label a value receives.

Words you will see

Branch
A block of instructions chosen by a condition.
elif
Another condition considered only if earlier branches did not match.
Indentation
Leading whitespace that marks the statements belonging to a block.

Order overlapping rules from specific to broad

The score is 82. score >= 90 is False, so Python skips the excellent print. It then evaluates score >= 70, which is True, and prints good. The else body is skipped. Only one label is produced by this chain.

Every score at least 90 is also at least 70. If the 70 rule came first, those excellent scores would be classified as good before the more specific rule was reached. Put the narrower threshold first when the categories overlap.

Make the block visible

The colon ends each branch header. The indented print belongs to that branch; an unindented statement after the chain runs regardless of which label was chosen. Use four spaces consistently rather than mixing tabs and spaces.

Use separate if statements when multiple independent actions should happen. Use an if/elif chain when the choices are alternatives. An else is a fallback, not a condition that means the same thing as the last successful test.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. score = 82

    Supply the score to classify.

  2. if score >= 90:

    The first test fails, so its body does not run.

  3. elif score >= 70:

    The next test succeeds.

  4. print("good")

    Print the selected label and skip the else branch.

An if/elif/else chain expresses alternatives. Put the more specific rule before the more general rule. Indentation defines the branch body; consistent four-space indentation makes structure visible.

Conceptual first-match decision, not a trace of edited code

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. First thresholdIf score is at least 90, choose excellent and stop selecting.
  2. Second thresholdOtherwise, test at least 70 and choose good if true.
  3. FallbackOnly if both tests fail, choose keep practising.
Predict before you run

Why does 82 produce good rather than two labels?

A meaningful thresholdPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Hit the upper threshold.

Try: Change score to 90.

The first branch prints excellent, including equality.

Observe an independent action.

Try: Add an unindented print("done") after the chain.

done prints after whichever label was selected.

Before you move on

If the same chain receives 95, which comparisons need to run?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Only score >= 90 is needed. It succeeds, prints excellent and skips all later branches, including the >= 70 comparison.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Boundary cases are part of the rule

A boundary is a value where a decision changes. Equality at that boundary is part of the requirement, not a detail to guess.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Shipping prices, age limits and validation often fail exactly at the threshold even when ordinary examples look correct.

Words you will see

Inclusive
The endpoint belongs to the accepted range, as in >=.
Exclusive
The endpoint is not included, as in >.
Boundary case
An input exactly at or immediately around a point where the rule changes.

Test the transition

The rule gives free shipping when the basket is at least 50. The sample checks 49, 50 and 51. The first is below the boundary and prints paid; the other two print free. Replacing >= with > would misclassify exactly 50.

The loop is only a way to exercise several fixed cases. The decision itself remains one if/else per basket. Writing two separate if statements with overlapping tests could perform two actions instead of choosing one shipping category.

Ask what is outside the domain

For this example, basket values are nonnegative integer units. If a real system accepts decimals, define currency precision and the threshold unit. If negative or missing baskets are possible, validate them before applying the ordinary shipping rule.

Do not silently treat every invalid input as paid. That hides data errors behind an apparently legitimate category. A decision table listing input ranges and labels is often clearer than a dense condition with many exceptions.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. for basket in [49, 50, 51]:

    Visit just below, exactly at and just above the threshold.

  2. if basket >= 50:

    Include equality in the free category.

  3. print(basket, "free")

    Display free for 50 and 51.

  4. print(basket, "paid")

    Display paid only for 49.

Before coding a threshold, decide what happens at equality. Test just below, exactly on and just above a boundary. Two independent if statements are not equivalent to an if/elif chain when both conditions can be true.

Predict before you run

Which sample input catches a mistaken > 50?

Check both sides of shippingPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Expose the boundary bug.

Try: Replace basket >= 50 with basket > 50.

Only the 50 line changes from free to paid.

Move the policy threshold.

Try: Change the threshold to 51 without changing the inputs.

49 and 50 print paid; 51 prints free.

Before you move on

A discount starts at 100 inclusive. What three nearby integer inputs should you check?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Check 99, 100 and 101. The first should not receive the discount; the other two should. The middle case distinguishes >= from >.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Keep the happy path visible

A guard handles an exceptional input early so the ordinary path can remain flat and readable.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A reservation rule is easier to inspect when invalid quantities and shortages are handled before the normal success result.

Words you will see

Guard clause
An early return or exception for a special case.
Return
End the current function call and supply its result.
Happy path
The ordinary successful case, after exceptional cases are excluded.

Exclude cases in a meaningful order

reserve checks wanted <= 0 first. Such a request returns invalid immediately, before any stock decision. It next checks whether the positive request exceeds stock and returns shortage. Only the remaining valid, affordable request returns reserved.

The three calls show each route. Returning from a guard ends that function call, not the entire script. The next print can call the function with another input. No stock is changed; this sample classifies a request rather than implementing inventory transactions.

Use guards for clarity, not cleverness

Without guards, you could nest the valid case under an if and then another if. Both structures can be correct. Prefer the one that lets a reader see the input contract and success rule without tracking several indentation levels.

Place side effects after validation, not inside a condition that might run only sometimes. A real reservation also needs a concurrency and persistence policy; a successful label from this pure function does not guarantee durable stock allocation.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. if wanted <= 0:

    Reject nonpositive requests first.

  2. return "invalid"

    Stop this call before checking stock.

  3. if wanted > stock:

    Detect insufficient stock for a valid request.

  4. return "reserved"

    The remaining request is positive and fits the available stock.

Inside a function, handle invalid or exceptional cases early with return or an exception, then write the normal path without layers of nesting. Avoid side effects hidden inside complex conditions.

Predict before you run

Does the first invalid call stop the later two prints?

Keep reservation decisions flatPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Check exact capacity.

Try: Change the final call to reserve(3, 3).

The final result remains reserved.

Reject negative requests.

Try: Change the first call to reserve(3, -1).

The first guard still returns invalid.

Before you move on

For reserve(3, 3), is the result shortage or reserved?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It is reserved. The request is positive and wanted > stock is False at equality, so it reaches the success return.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Branches translate policy into observable behaviour. A shipping threshold or score band is not fully specified until equality and invalid inputs have meanings. Begin with a decision table covering representative values, then implement the table; this is more reliable than inventing conditions while looking only at the happy-path example.

Follow the mechanism step by step

An if/elif chain tests conditions from top to bottom and executes only the first matching branch. Two independent if statements can both run. Python uses indentation to determine each branch body, so visual alignment is executable structure, not merely formatting. Short-circuit evaluation can prevent evaluating the right operand when the left already determines the result.

Work through a concrete application

For score bands, place the most specific high threshold first, then the broader lower band. Check scores just below, on and above each boundary. Extract the decision into a function returning a category so the caller can decide whether to print, persist or display it. Keep unrelated network or file operations out of the classification logic.

Failure cases and misleading shortcuts

An else branch should not silently convert every invalid value into a valid lowest category. Validate types and domain bounds separately when necessary. Avoid using and/or as an obscure conditional expression when a false-like valid value could select the wrong operand. Nested ternaries can conceal overlapping rules that a clear branch structure would expose.

Cost, ownership and alternatives

A short fixed chain usually has bounded evaluation cost, but the conditions themselves may be expensive or side-effecting. Order cheap validation before costly work when the semantics allow it. Early returns can reduce nesting inside a function, while a data-driven mapping may be more appropriate for exact key-to-action selection.

Verify the contract

Test every branch and every threshold, including values that satisfy more than one condition. Confirm that invalid inputs raise or report the intended error. A high line-coverage number can still miss a mistaken >= versus > comparison; boundary assertions need to express the policy explicitly.

Transfer question: A discount rule gives members 10% and large orders 15%. Should it be two if statements?

First clarify whether discounts combine, whether the larger one wins or whether membership has priority. The code structure follows that policy. An if/elif chain expresses exclusive alternatives, while independent calculations may be appropriate for a documented combination rule.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Which branch order handles scores correctly?
TRANSFER THE IDEA

Shipping rule

Print free when the basket is at least 50; otherwise print paid.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: classify shipping

Apply an inclusive free-shipping threshold.

The contract

  • basket is a nonnegative integer in fixed units.
  • Return 'free' for basket >= 50 and 'paid' otherwise, as text.
  • Zero is valid; no printing, input reading or mutation.
Guided: classify shippingPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. below threshold
    from copy import deepcopy
    args = (49,)
    before = deepcopy(args)
    expected = "paid"
    result = shipping_label(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for below threshold"
    assert args == before, "Preserve every supplied input"
  2. exact threshold
    from copy import deepcopy
    args = (50,)
    before = deepcopy(args)
    expected = "free"
    result = shipping_label(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for exact threshold"
    assert args == before, "Preserve every supplied input"
  3. above threshold
    from copy import deepcopy
    args = (51,)
    before = deepcopy(args)
    expected = "free"
    result = shipping_label(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for above threshold"
    assert args == before, "Preserve every supplied input"
  4. zero basket
    from copy import deepcopy
    args = (0,)
    before = deepcopy(args)
    expected = "paid"
    result = shipping_label(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero basket"
    assert args == before, "Preserve every supplied input"
  5. small basket
    from copy import deepcopy
    args = (1,)
    before = deepcopy(args)
    expected = "paid"
    result = shipping_label(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for small basket"
    assert args == before, "Preserve every supplied input"
  6. large basket
    from copy import deepcopy
    args = (500,)
    before = deepcopy(args)
    expected = "free"
    result = shipping_label(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for large basket"
    assert args == before, "Preserve every supplied input"
    Which fixture separates > from >=?

    Exactly 50 does; other nearby values cannot catch that boundary error. The classifier uses one comparison and fixed-size output.

    GUIDED PRACTICE

    Guided: classify scores with an invalid range

    Validate a score before applying overlapping thresholds.

    The contract

    • score is an integer; values outside 0 through 100 are invalid.
    • Return 'invalid' outside that domain; otherwise 'excellent' at 90+, 'good' at 70+, and 'keep practising' below 70.
    • Use exactly those strings and leave inputs unchanged. Classify only one category.
    Guided: classify scores with an invalid rangePYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. excellent boundary
      from copy import deepcopy
      args = (90,)
      before = deepcopy(args)
      expected = "excellent"
      result = score_label(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for excellent boundary"
      assert args == before, "Preserve every supplied input"
    2. good boundary
      from copy import deepcopy
      args = (70,)
      before = deepcopy(args)
      expected = "good"
      result = score_label(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for good boundary"
      assert args == before, "Preserve every supplied input"
    3. below good
      from copy import deepcopy
      args = (69,)
      before = deepcopy(args)
      expected = "keep practising"
      result = score_label(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for below good"
      assert args == before, "Preserve every supplied input"
    4. valid upper limit
      from copy import deepcopy
      args = (100,)
      before = deepcopy(args)
      expected = "excellent"
      result = score_label(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for valid upper limit"
      assert args == before, "Preserve every supplied input"
    5. negative invalid
      from copy import deepcopy
      args = (-1,)
      before = deepcopy(args)
      expected = "invalid"
      result = score_label(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for negative invalid"
      assert args == before, "Preserve every supplied input"
    6. over limit invalid
      from copy import deepcopy
      args = (101,)
      before = deepcopy(args)
      expected = "invalid"
      result = score_label(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for over limit invalid"
      assert args == before, "Preserve every supplied input"
      Why not classify 101 as excellent?

      The stated domain excludes it. Validation precedes category selection. A bounded number of comparisons gives fixed-count work for bounded-size integers.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: prioritise validation over stock

      A stock decision now has two invalid-input rules and an explicit success boundary.

      The contract

      • stock and requested are integers.
      • Return 'invalid' if stock < 0 or requested <= 0, even if a shortage comparison would also be true.
      • Otherwise return 'shortage' if requested > stock, and 'reserved' if it fits. This is a pure classification, not a stock mutation.
      Transfer: prioritise validation over stockPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. ordinary reservation
        from copy import deepcopy
        args = (5, 2)
        before = deepcopy(args)
        expected = "reserved"
        result = order_decision(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for ordinary reservation"
        assert args == before, "Preserve every supplied input"
      2. exact stock
        from copy import deepcopy
        args = (3, 3)
        before = deepcopy(args)
        expected = "reserved"
        result = order_decision(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for exact stock"
        assert args == before, "Preserve every supplied input"
      3. shortage
        from copy import deepcopy
        args = (3, 4)
        before = deepcopy(args)
        expected = "shortage"
        result = order_decision(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for shortage"
        assert args == before, "Preserve every supplied input"
      4. zero request
        from copy import deepcopy
        args = (3, 0)
        before = deepcopy(args)
        expected = "invalid"
        result = order_decision(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero request"
        assert args == before, "Preserve every supplied input"
      5. negative stock
        from copy import deepcopy
        args = (-1, 1)
        before = deepcopy(args)
        expected = "invalid"
        result = order_decision(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for negative stock"
        assert args == before, "Preserve every supplied input"
      6. empty stock
        from copy import deepcopy
        args = (0, 1)
        before = deepcopy(args)
        expected = "shortage"
        result = order_decision(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty stock"
        assert args == before, "Preserve every supplied input"
        Why not test shortage first?

        A negative stock count must be reported invalid rather than disguised as an ordinary shortage. The requirement prioritises validation; no inventory is actually reserved by returning a label.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Expressions versus statements

        A conditional expression chooses one value. An if statement chooses a block of actions. Boolean and/or also choose operands, but their truth rules can differ from an absence rule.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A default should not replace a deliberately supplied zero unless the requirement says zero is missing.

        Words you will see

        Expression
        Code that produces a value.
        Conditional expression
        yes_value if condition else no_value.
        Operand
        A value used by an operator; and/or return a selected operand.

        Read the chosen values

        supplied is 0. supplied or 10 returns 10 because zero is falsy. supplied if supplied is not None else 10 returns 0 because zero is not None. These are different defaulting policies even though they often agree for positive numbers.

        The final expression chooses 'empty' when supplied equals zero. Its condition sits between the two possible results. Only the selected result expression is evaluated. Use it for a short value choice, not a long nested decision tree.

        Choose a readable form

        Use an if statement when branches perform several actions or deserve explanatory names. Use a conditional expression when a single short assignment benefits from keeping the two alternatives together. Parenthesised code is not automatically easier to understand.

        Do not use a and b or c as a universal substitute for b if a else c: a falsy b can make it select c unexpectedly. Write the actual condition that distinguishes absent data from valid empty or zero values.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. print(supplied or 10)

          Falsy zero causes or to select 10.

        2. print(supplied if supplied is not None else 10)

          The explicit absence check keeps zero.

        3. print("empty" if supplied == 0 else "nonzero")

          Choose one short message from a comparison.

        x if condition else y is an expression that chooses a value. Use it for short choices, not nested business logic. Boolean and/or return operands, not necessarily True/False; an explicit conditional can be clearer.

        Predict before you run

        Why do the first two outputs differ?

        Zero is not necessarily missingPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Supply no value.

        Try: Set supplied = None.

        The first two lines both display 10; the final comparison selects nonzero.

        Supply a positive value.

        Try: Set supplied = 4.

        Both defaults keep 4 and the final line displays nonzero.

        Before you move on

        If an optional limit is 0 to mean 'show nothing', should limit or 20 implement a missing-only default?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. It replaces the valid zero with 20. Use limit if limit is not None else 20 when only None means missing.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Pattern matching has a different purpose

        Pattern matching selects a branch by the shape and contents of a value. A pattern can also bind parts of that value to names.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A command represented by several fields needs structure checks as well as value checks. A simple numeric threshold is usually still clearer with if.

        Words you will see

        Pattern
        A description of a value's structure and selected contents.
        Capture
        Binding a matched part to a name.
        Guard
        An extra if condition after a pattern that must also succeed.

        Match structure, then a requirement

        The input is a two-element tuple whose first element is 'move'. The first case matches that literal and captures the second element as distance. Its guard distance > 0 succeeds for 3, so print displays move 3.

        A zero or negative distance fits the shape but fails the guard. Python then considers the next matching 'move' case and prints invalid distance. The final underscore case is a wildcard for everything else. This syntax requires Python 3.10 or later.

        Do not accidentally capture a constant

        A bare name in a pattern usually captures a value rather than comparing with an existing variable of that name. Use literal patterns for these fixed strings. A dotted name can refer to a qualified constant, but do not assume any unqualified name means equality.

        Use match when shape matters and several structured alternatives need unpacking. Use if/elif for simple comparisons or when type validation must be very explicit. A guard may raise an error if its captured value has an unsupported type; this example deliberately supplies an integer distance.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. command = ("move", 3)

          Provide the structured command.

        2. case ("move", distance) if distance > 0:

          Check the literal, capture 3 and test that it is positive.

        3. print("move", distance)

          Display the selected command and skip later cases.

        4. case _:

          Keep a fallback for inputs not accepted by the earlier patterns.

        match supports structural patterns on Python 3.10+, not just equality checks. Guard capture patterns carefully; a bare name can capture rather than compare. Do not use a newer construct only to replace a simple readable if.

        Predict before you run

        Which part distinguishes a valid positive move?

        Match a command shapePYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Fail the guard.

        Try: Set command = ("move", 0).

        It prints invalid distance.

        Change the command word.

        Try: Set command = ("wait", 3).

        Neither move pattern fits, so it prints unknown command.

        Before you move on

        What would ('move', 0) print with this case order?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        It prints invalid distance. The first pattern fits but its guard fails; the next move pattern succeeds.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.