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 14 / FUNCTIONS AND REUSABLE CODE

Functions that keep promises

Give a unit of work a name, inputs and a return contract.

FoundationTutorial 13 min core+10 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: 13 minutes; optional deep dive: 10 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
  • Define and call functions
  • Separate return from print
  • Avoid mutable defaults
01

Name the transformation

A function names a piece of work. Arguments go in, and return sends a result back so another expression can use it.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Calculate a subtotal once, then let the caller display it, double it or compare it. This keeps calculation separate from presentation.

Words you will see

Parameter
A name in a function definition, such as prices.
Argument
The value supplied by a call, such as [5, 8, 2].
Return
End this call and give a value back; it does not display that value.

Follow the call and the result

def subtotal(prices): creates a function; the indented body does not run until the call. subtotal([5, 8, 2]) binds prices to that list for this call. sum adds its three numbers to get 15. return ends the call with 15, and assignment binds result to that number.

print(result) displays 15. result * 2 produces 30 without calling subtotal again. If the function printed 15 instead of returning it, result would be None and multiplying it would raise TypeError.

Specify the small promise

Here prices is a list of numbers and the result is their sum, including repeated numbers. sum([]) is 0. Negative numbers contribute negatively; they are not silently discarded. Reading the list does not change it.

Use a plain loop if each price needs extra decisions. A return exits immediately, so putting it inside that loop accidentally returns a partial subtotal. A function call is not a new process or a separate browser worker.

The original example, step by step

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

  1. def subtotal(prices):

    Create the named operation with one input.

  2. return sum(prices)

    Return 15 for these prices; do not print inside the calculation.

  3. result = subtotal([5, 8, 2])

    Store the returned number, not the function itself.

  4. print(result * 2)

    Reuse 15 to print 30.

A function packages a responsibility. Parameters receive arguments; return sends a result to the caller. A function without an explicit return returns None. Printing displays a value but does not return it.

Conceptual return-value flow for the original subtotal, not an instrumented execution trace.

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

  1. Input bindingsubtotal([5, 8, 2]) → prices refers to the supplied list.
  2. Calculationsum(prices) → 15; return passes that number to the caller.
  3. Caller choiceresult → 15; print(result) displays 15; print(result * 2) displays 30.
Predict before you run

What are the two printed numbers?

Return a reusable resultPYTHON 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.

Include a refund.

Try: Change the input to [5, -2, 2].

The subtotal is 5 and the doubled result is 10.

Test no prices.

Try: Call subtotal([]) instead.

The prints are 0 and 0, because sum has a zero starting total.

Before you move on

If subtotal is called with [4, 4, -1], what is returned and is the list changed?

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 returns 7. Both 4s count, the -1 is included, and sum does not mutate the list.

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

Make calls readable

A readable call tells the reader what each argument means. A focused function calculates one result without unrelated side effects.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A named option is clearer than guessing whether True means rounding, tax or delivery. Keeping calculation free of file writes makes it usable in browser Python.

Words you will see

Keyword argument
An argument written with its parameter name, such as fee=2.
Default
The value used when a caller omits an optional argument.
Side effect
An observable change beyond returning a value, such as changing an input or writing a file.

Give options names

In checkout(prices, fee=0), prices is required and fee is optional. checkout([5, 8], fee=2) binds the list to prices and 2 to fee. The function adds the subtotal and fee and returns 15. Naming fee communicates intent even though this signature also permits it positionally.

A zero fee needs no special branch: 13 + 0 is 13. A negative fee would act as a discount under this arithmetic contract. Validate it separately if the business rule forbids discounts.

Leave presentation to the caller

The function reads prices and returns a number. The outer print is responsible for display. It neither sends a payment nor records an order; a displayed total is not evidence that an external action occurred.

Avoid mixing file access or network calls into this example. Pure arithmetic can run in browser Python without an operating-system service. An empty prices list still returns the fee.

The original example, step by step

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

  1. def checkout(prices, fee=0):

    Declare one required input and a zero default.

  2. return sum(prices) + fee

    Add all prices first, then the fee once.

  3. print(checkout([], fee=2))

    The empty sum is zero, so this prints 2.

Use descriptive parameter names and keyword arguments for values whose meaning is otherwise unclear. Keep functions focused; a function that calculates and also writes files is harder to test than a pure calculation.

Predict before you run

What does the empty checkout print?

Name the feePYTHON 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.

Change the named option.

Try: Replace fee=2 with fee=4 in both calls.

The outputs become 17 and 4.

Try the default.

Try: Remove fee=2 from the first call.

The first result becomes 13; the second remains 2.

Before you move on

What does checkout([3, 3], fee=1) return, and what if fee is omitted?

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 returns 7 with the explicit fee and 6 with the default. The fee is added once per call, not once per price.

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

Document the contract

A function contract states which inputs are allowed, what comes back and what happens at the boundary.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A caller needs to know whether an empty average means zero or an error. Make that decision explicit rather than discovering a division error during use.

Words you will see

Docstring
A string at the start of a function body describing its purpose or contract.
Boundary case
An input at an edge of the rules, such as an empty list.
Mean
The sum of numbers divided by how many numbers there are.

Check before dividing

average accepts a list of numbers and returns zero for no numbers. if not values tests emptiness here. That branch returns immediately; the later division is never attempted for []. For [2, 4, 6], the sum is 12 and the length is 3, so / returns the float 4.0.

Returning zero on empty input is a deliberate teaching contract, not a universal mathematical rule. In another API a missing measurement may deserve None or ValueError instead. Never silently treat every exception as an empty list.

Keep the promise narrow

The example does not validate arbitrary objects or parse text. A string element may make sum raise TypeError. The docstring describes numeric input, and tests should include negative and repeated numbers as valid cases.

The calculation reads but does not sort or remove elements. It makes one summing pass, so time is O(n) for n numbers under ordinary numeric operations and extra working space is O(1), excluding the input and result.

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 not values:

    Decide whether there are any measurements before division.

  2. return 0

    Use the documented empty result and leave the call.

  3. return sum(values) / len(values)

    Compute 12 / 3 as 4.0 for the nonempty list.

State valid inputs, return value and errors. A short docstring helps future callers. Test empty and boundary inputs rather than assuming a function only receives the happy path.

Predict before you run

Why is the second call safe?

State the empty-average rulePYTHON 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.

Test a singleton.

Try: Replace [2, 4, 6] with [7].

The result is 7.0 because one measurement has its own value as mean.

Test cancellation.

Try: Use [-4, 4] in the first call.

The result is 0.0, a nonempty mean rather than the empty branch.

Before you move on

For [-2, 2, 2], is the mean 0 or 2/3?

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 2/3. There are three measurements, including the repeated 2. The numerator is 2 and the denominator is 3.

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

A function should provide a small contract that a caller can explain: accepted inputs, returned result, side effects and possible errors. Extracting a function is useful when it separates a transformation from I/O or gives a coherent operation a name, not merely when it reduces a file's line count.

Follow the mechanism step by step

Calling binds arguments to parameters and executes the body. return ends that invocation and passes a value to the caller; reaching the end returns None. A mutable argument is still the caller's referenced object unless the function constructs an independent value. Rebinding a parameter does not rebind the caller's name.

Work through a concrete application

Design an average function by deciding the empty-input policy first. Compute from input values and return the result; print only at the outer application boundary. Then test a normal list, one item and an empty list. Document whether iterators are accepted, because calling len and traversing twice assumes more than a generic iterable.

Failure cases and misleading shortcuts

Printing a correct value is not the same as returning it, and a caller may need the result for further computation. Mutable defaults persist across calls. Hidden global configuration, cached clocks or network requests can also make a seemingly pure helper depend on state that tests did not supply.

Cost, ownership and alternatives

A focused pure function is usually easier to test and reuse than one that parses, computes, writes and logs every record. Copying inputs to avoid mutation has a measurable cost and may remain shallow. Prefer a clear ownership promise over assuming either every function mutates or every function must deep-copy everything.

Verify the contract

Test the public contract rather than local variable names or exact implementation steps. Include repeated invocations to detect retained state, caller-owned input checks for non-mutation promises and explicit exception tests. If the function accepts a stream, test a one-pass iterator as well as a list so accidental multiple consumption becomes visible.

Transfer question: Should average([]) return zero?

That is a domain decision, not a universal Python rule. Zero can be confused with a real average of zero. A missing-value result or explicit exception may be better. Choose, document and test the policy before implementing callers that depend on it.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

What does a function with no return return?
When is a default argument evaluated?
TRANSFER THE IDEA

A safe average

Return zero for an empty list; otherwise return the mean.

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

Return the whole subtotal

Return a number the caller can reuse, without changing prices.

The contract

  • Implement subtotal(prices) for a list of integers; return an int, never print in place of returning.
  • Count every repeated and negative value; [] returns 0.
  • Do not mutate prices. No imports, files, network or process work is needed.
Return the whole subtotalPYTHON 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
    r = subtotal([5, 8, 2]); assert type(r) is int and r == 15
  2. empty
    r = subtotal([]); assert type(r) is int and r == 0
  3. repeated
    r = subtotal([4, 4, 4]); assert type(r) is int and r == 12
  4. negative
    r = subtotal([-5, 2]); assert type(r) is int and r == -3
  5. singleton
    r = subtotal([9]); assert type(r) is int and r == 9
  6. preservation
    p = [3, 1, 3]; r = subtotal(p); assert type(r) is int and r == 7 and p == [3, 1, 3]
    Why should return be after an explicit loop?

    A return inside the loop stops on the first price. One pass costs O(n) time and O(1) extra working space for ordinary fixed-size arithmetic; Python integers can grow.

    GUIDED PRACTICE

    Respect a supplied basket

    Create a fresh default basket, but append into a supplied basket.

    The contract

    • Implement add_item(value, items=None); value is a string and items is None or a list of strings.
    • Return the exact supplied list after appending once; duplicates and order are retained.
    • An omitted or explicit None list must be fresh on every call. Mutating a supplied list is intentional.
    Respect a supplied basketPYTHON 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. omitted
      r = add_item('tea'); assert type(r) is list and r == ['tea']
    2. independence
      a = add_item('tea'); b = add_item('rice'); assert type(a) is list and type(b) is list and a == ['tea'] and b == ['rice'] and a is not b
    3. empty identity
      p = []; r = add_item('x', p); assert type(r) is list and r is p and p == ['x']
    4. order
      p = ['b', 'a']; r = add_item('c', p); assert type(r) is list and r is p and r == ['b', 'a', 'c']
    5. duplicates
      p = ['x']; r = add_item('x', p); assert type(r) is list and r is p and r == ['x', 'x']
    6. explicit none
      a = add_item('', None); b = add_item('z', None); assert type(a) is list and type(b) is list and a == [''] and b == ['z'] and a is not b
      Why not write if not items?

      It treats an explicitly supplied empty list as absence and replaces it. Append is amortized O(1); creating an omitted empty basket takes O(1) initial space, then grows with appended items.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: an empty-aware mean

      Change from summing to averaging, with an explicit empty rule.

      The contract

      • Implement average(values) for lists of integers.
      • Return float(sum / count) for nonempty input and integer 0 for []; count duplicates separately.
      • Do not mutate input. Do not round or use integer division. Other input types are outside this contract.
      Transfer: an empty-aware meanPYTHON 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 mean
        r = average([2, 4, 6]); assert type(r) is float and r == 4.0
      2. empty rule
        r = average([]); assert type(r) is int and r == 0
      3. fraction
        r = average([1, 2]); assert type(r) is float and r == 1.5
      4. repeated mean
        r = average([2, 2, 8]); assert type(r) is float and r == 4.0
      5. singleton negative
        r = average([-7]); assert type(r) is float and r == -7.0
      6. preservation
        p = [4, -4, 6]; r = average(p); assert type(r) is float and r == 2.0 and p == [4, -4, 6]
        What changed from subtotal?

        The denominator and the empty-input policy are new. Sum still requires O(n) time; the function needs O(1) extra working space for ordinary arithmetic, without copying the list.

        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

        Default values are evaluated once

        A default expression is evaluated when def runs. Use None to request a new list per omitted argument instead of sharing a default list.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Independent calls that add different shopping items should not unexpectedly share earlier items.

        Words you will see

        Sentinel
        A distinguished value that signals a special case; None means no list was supplied here.
        Identity
        Whether two names refer to the very same object, tested with is.
        Mutation
        Changing an existing object, such as append changing a list.

        Choose the list at call time

        The default is None, an immutable absence marker. On each call without items, items is None is true and [] creates a new list. append changes that chosen list and return exposes it. The two displayed lists are independent.

        If the signature used items=[], that list would be made when the definition executes. Later calls omitting items would reuse it. The second call would then display ['tea', 'rice'], not the reference output.

        Explicit sharing is still sharing

        Passing an existing list intentionally bypasses the None branch. add_item('tea', basket) appends into basket and returns that same object. The safe default prevents accidental sharing; it does not promise to copy a supplied list.

        Test items is None, not if not items. An explicitly supplied empty list is false in a condition, but it is still caller-owned and should be the object that receives the item. Append is amortized O(1) in ordinary list implementations, not a worst-case guarantee for every append.

        The original example, step by step

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

        1. def add_item(value, items=None):

          Evaluate the None default once without allocating a shared list.

        2. if items is None:

          Distinguish omission from a supplied empty list.

        3. items = []

          Allocate a fresh list for this omitted argument.

        4. items.append(value)

          Mutate the chosen list before returning it.

        A default list can accumulate state between calls. Use None as a sentinel and create a fresh list inside when no value is supplied.

        Predict before you run

        Why does rice not follow tea in the second output?

        A fresh defaultPYTHON 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.

        Request deliberate sharing.

        Try: Create basket = []; pass basket as the second argument to both calls.

        The second output includes tea and rice because both calls mutate basket.

        Expose the unsafe default.

        Try: Use items=[] and remove the None branch, then run both calls.

        The shared default accumulates tea and rice. Restore the None version afterwards.

        Before you move on

        If basket = [], what should add_item('oats', basket) return and what happens to basket?

        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 returns that exact basket object, now ['oats']. The supplied list is not replaced just because it was empty.

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

        Scope and ownership

        A parameter is a local name for an object. Rebinding that name and mutating that object are different actions.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Explain why one helper changes the caller's basket while another only changes its own local name. This avoids hidden ownership bugs.

        Words you will see

        Binding
        A name's connection to an object.
        Rebinding
        Pointing a name at a different object.
        Borrowed input
        An object supplied by a caller whose ownership rules the function must respect.

        Trace the two operations

        basket and items initially name the same list. items.append('tea') changes that list, so basket now contains tea too. items = ['rice'] then binds only the local items name to a new list. It does not redirect basket.

        return items sends the new rice list to the caller, which binds result to it. Printing basket shows tea; printing result shows rice. There are now two lists, not one list that somehow remembers two contents.

        Choose ownership deliberately

        If a helper promises not to mutate a flat input list, make a copy before appending, or build a new list with addition. A shallow copy shares any nested objects: it does not give independent ownership of every nested value.

        Local names disappear after a call unless something retains their objects. Prefer explicit inputs and returned results over changing globals. The example uses no global declaration, file, process or network operation.

        The original example, step by step

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

        1. items.append('tea')

          Change the caller's list through the local reference.

        2. items = ['rice']

          Rebind only the local name to a new list.

        3. result = prepare(basket)

          Keep the new returned list separately from basket.

        Local assignment binds a local name unless declared otherwise. Passing a list passes an object reference; mutation is visible to the caller, rebinding the parameter is not. Prefer explicit inputs/outputs to hidden global dependencies.

        Predict before you run

        Which list contains tea at the end?

        Mutation before rebindingPYTHON 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.

        Return the shared object.

        Try: Remove items = ['rice'].

        Both prints show ['tea'], and result is basket is True.

        Avoid the input mutation.

        Try: Insert items = list(items) before append.

        basket remains empty; result is still ['rice'] because the later rebinding is unchanged.

        Before you move on

        If append is removed, what does the final basket contain?

        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 stays []. Rebinding items to ['rice'] alone does not change the original list or the caller's name.

        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.