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

Design clear function signatures

Use positional-only, keyword-only, variadic and unpacked arguments intentionally.

IntermediateTutorial 14 min core+12 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 who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 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
  • Explain make ambiguous calls impossible
  • Apply collect and forward arguments carefully
  • Reason about validation and ownership
01

Make ambiguous calls impossible

A signature is the set of calling rules in def: which arguments are required, positional-only or named options.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Prevent an ambiguous boolean argument from silently becoming a different option when an API grows.

Words you will see

Positional-only
A parameter before / must be supplied by position.
Keyword-only
A parameter after a bare * must be supplied by name.
Binding
Matching supplied arguments to parameters before the body runs.

Read the separators

In def resize(width, /, *, scale=1), width is positional-only and scale is keyword-only. The slash and star are separators, not values passed to the function. resize(8, scale=2) binds width to 8 and scale to 2, then returns 16.

resize(width=8) and resize(8, 2) raise TypeError before entering the body. This is different from a valid call whose values violate a business rule. A signature controls call shape, not whether a number is positive.

Choose compatibility deliberately

Making width positional-only leaves its internal parameter name less exposed to callers. Naming scale keeps the optional setting visible at the call site. Do not introduce either restriction into an established API without checking existing callers.

Defaults are evaluated when the definition runs. The integer 1 is safe to share here. No mutable default is allocated, and the empty-argument call is invalid because width is required.

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 resize(width, /, *, scale=1):

    Mark width positional-only and scale keyword-only.

  2. return width * scale

    Multiply the two bound values.

  3. print(resize(8))

    Use the default scale of 1 and print 8.

A slash marks parameters before it positional-only; a bare star makes subsequent parameters keyword-only. Keyword-only flags make calls such as resize(image, width=80, preserve_ratio=True) easier to review. Defaults are evaluated when the definition executes, not for each call.

Predict before you run

Which call prints 16?

Separate required input and named optionPYTHON 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.

Try the invalid positional option.

Try: Change resize(8, scale=2) to resize(8, 2).

TypeError is visible; no hidden fallback supplies a value.

Change the default.

Try: Change scale=1 in def to scale=3.

The explicit scale call remains 16; the omitted-scale call becomes 24.

Before you move on

Is resize(5, scale=3) valid, and is resize(5, 3) valid?

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

The named-scale call returns 15. The second call is invalid because scale is keyword-only and raises TypeError.

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

Collect and forward arguments carefully

A star collects or unpacks positional arguments; two stars collect or unpack named arguments. Their role depends on whether you are defining or calling.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Forward a group of known options without losing their names, but still let misspelled options fail.

Words you will see

*args
In a definition, collect extra positional arguments in a tuple.
**kwargs
In a definition, collect extra keyword arguments in a dictionary.
Unpacking
At a call, expand a sequence with * or a mapping with ** into arguments.

Collect, then forward

relay receives ('api',) as args and {'uppercase': True} as kwargs. target(*args, **kwargs) expands them into target('api', uppercase=True). The target returns 'API', and relay must return it too.

The names args and kwargs are conventions; the stars do the work. An empty tuple or mapping forwards nothing. This relay does not sort, merge or stringify the values.

Keep errors useful

Accepting **kwargs at the relay does not mean every option is supported. target has a fixed signature, so passing unknown=True through relay raises TypeError. Do not discard unknown options and fabricate success.

Two sources cannot supply the same parameter twice. target('api', name='db') is an error. Dictionary unpacking at a call requires string keyword keys. Forwarding is not validation of the values themselves.

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 relay(*args, **kwargs):

    Collect the positional tuple and keyword dictionary.

  2. return target(*args, **kwargs)

    Unpack both collections at the call and return the target result.

  3. print(relay('db'))

    With no keyword option, target uses False.

*args gathers extra positional arguments into a tuple; **kwargs gathers named arguments into a dict. At a call site, * and ** unpack values. Do not accept arbitrary kwargs merely to suppress errors: validate supported names and preserve useful TypeError diagnostics.

Predict before you run

What does relay('db') print?

Forward a known optionPYTHON 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.

Forward from stored data.

Try: Replace the first call with relay(*['api'], **{'uppercase': True}).

It still prints API; unpacking can occur at both call boundaries.

Test an unsupported option.

Try: Change uppercase=True to loud=True.

target raises TypeError rather than ignoring a typo.

Before you move on

What happens to relay('web', unknown=True)?

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

The relay accepts the keyword, but forwarding reaches target, whose signature rejects unknown with TypeError. No supported option is silently invented.

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

Separate identity from options

Combining /, *tags and a named option can keep identity positional while accepting any number of labels.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

An API description can have zero, one or several tags without an obscure list argument or an ambiguous uppercase flag.

Words you will see

Variadic
Accepting a variable number of arguments.
join
A string method connecting text items with a separator.
Conditional expression
a if condition else b chooses which expression supplies the value.

Read this actual signature

describe takes name before /, so name is positional-only. *tags gathers all remaining positional labels into a tuple. Parameters after *tags are keyword-only without another bare star; uppercase defaults to False.

The call binds name='api', tags=('fast', 'tested') and uppercase=True. ', '.join(tags) produces 'fast, tested'. The f-string adds 'api: ', and upper converts the complete text to 'API: FAST, TESTED'.

Handle fewer labels without special cases

No tags means an empty tuple. Joining it returns '', so describe('api') returns 'api: ' with a trailing space. That output is honest to this formatting contract; do not pretend the original trims it.

The labels must be strings for join. A numeric tag raises TypeError. uppercase selects formatting but is not validated as a literal bool by Python's signature. Add validation explicitly if that is part of an API's promise.

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 describe(name, /, *tags, uppercase=False):

    Separate identity, collected labels and a named option.

  2. text = f'{name}: {", ".join(tags)}'

    Build api: fast, tested with comma-space between tags.

  3. return text.upper() if uppercase else text

    Return the uppercase branch for this call.

name is positional-only, tags collects positional labels, and uppercase must be named. The function returns a reusable value rather than only printing.

Conceptual argument binding for describe; separators are calling rules, not runtime input values.

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

  1. Identity'api' → name; / requires this argument to be positional.
  2. Collected labels'fast', 'tested' → tags tuple; their order is retained.
  3. Named optionuppercase=True → uppercase; it is not another entry in tags.
  4. Result'api: fast, tested' → upper() → 'API: FAST, TESTED'.
Predict before you run

What is the complete original output?

Separate identity from optionsPYTHON 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.

Try no tags.

Try: Change the call to print(repr(describe('api'))).

repr displays 'api: ', making the trailing space visible.

Keep mixed case.

Try: Set uppercase=False in the original call.

It prints api: fast, tested without changing the tags or their order.

Before you move on

What is describe('db', 'small') with uppercase 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 is 'db: small'. The single tag joins unchanged, and the default False leaves the text's case alone.

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 signature is part of an API's user experience. It communicates which values are required, which names carry meaning and which options can safely gain defaults. A call such as resize(image, 80, True) is harder to review than one that explicitly names the width and ratio policy.

Follow the mechanism step by step

Parameters before / are positional-only; parameters after a bare * are keyword-only. *args collects surplus positional values into a tuple, while **kwargs collects named values into a dict. At a call site the same punctuation unpacks an iterable or mapping, which is a related but distinct operation.

Work through a concrete application

Design a report function with a required record stream and keyword-only output options. Make changing a formatting flag explicit at call sites. Reject unsupported keyword names rather than forwarding them through layers until a distant function fails. If a wrapper forwards arbitrary arguments, preserve the original return and exception behaviour as well.

Failure cases and misleading shortcuts

Defaults are evaluated at definition time, so a mutable default can retain state. Renaming a public keyword parameter breaks existing keyword callers even when the implementation is unchanged. Reordering positional parameters can be worse because calls may remain syntactically valid while silently changing meaning.

Cost, ownership and alternatives

A broad variadic signature can be useful for adapters, but weakens discoverability and static checking when used everywhere. Prefer explicit parameters at domain boundaries. Parameter binding overhead is rarely the performance bottleneck compared with the work inside the function; optimise clarity before micro-benchmarking invocation syntax.

Verify the contract

Test the intended calling forms and explicitly forbidden ones, including missing required values, positional use of keyword-only options and duplicate values supplied through both unpacking and explicit keywords. Add compatibility tests before evolving a public API, and distinguish argument-shape TypeError from domain validation failures.

Transfer question: Why might a library deliberately make a parameter positional-only?

It can prevent callers from depending on an internal parameter name and allow a mapping of keyword values to use the same name independently. The trade-off is less self-documenting calls, so use it when the library's compatibility or semantic needs justify that restriction.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

Which parameter must be passed by name in def f(x, *, limit=10)?
TRANSFER THE IDEA

Rebuild: Separate identity from options

Without copying the worked code, reproduce its observable contract: name is positional-only, tags collects positional labels, and uppercase must be named. The function returns a reusable value rather than only printing. Then change one boundary input and explain the result.

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

Separate identity and formatting

Return a label with positional-only identity and a keyword-only style option.

The contract

  • Implement render_label(name, /, *, uppercase=False) for strings and a bool formatting flag.
  • Return the string unchanged by default or uppercased when True; empty strings remain empty.
  • Reject a keyword name and a positional uppercase option with TypeError through the signature. No external operations.
Separate identity and formattingPYTHON 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. default
    r = render_label('Api'); assert type(r) is str and r == 'Api'
  2. uppercase
    r = render_label('Api', uppercase=True); assert type(r) is str and r == 'API'
  3. empty
    r = render_label('', uppercase=True); assert type(r) is str and r == ''
  4. punctuation
    r = render_label('a-a 2', uppercase=True); assert type(r) is str and r == 'A-A 2'
  5. positional-only rule
    from inspect import signature
    p = signature(render_label).parameters
    r = render_label('db'); assert type(r) is str and r == 'db' and p['name'].kind.name == 'POSITIONAL_ONLY'
  6. keyword-only rule
    from inspect import signature
    p = signature(render_label).parameters
    r = render_label('db', uppercase=False); assert type(r) is str and r == 'db' and p['uppercase'].kind.name == 'KEYWORD_ONLY'
    Why are signature checks combined with result checks?

    A pass body can have the correct parameter kinds yet no usable result. Both binding and behavior matter. Case conversion takes O(n) time and up to O(n) result space for n characters.

    GUIDED PRACTICE

    Collect and join ordered tags

    Accept any number of positional tags while keeping the separator named.

    The contract

    • Implement tag_line(*tags, separator=', '); tags and separator are strings.
    • Return tags joined in given order, including repeated and empty tags. No tags returns ''.
    • separator must be keyword-only; no input is mutated. Non-string tags are outside the contract.
    Collect and join ordered tagsPYTHON 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 = tag_line('fast', 'tested'); assert type(r) is str and r == 'fast, tested'
    2. empty
      r = tag_line(); assert type(r) is str and r == ''
    3. repetition
      r = tag_line('x', 'x', 'y'); assert type(r) is str and r == 'x, x, y'
    4. custom separator
      r = tag_line('b', 'a', separator='|'); assert type(r) is str and r == 'b|a'
    5. empty tag
      r = tag_line('', 'x', separator=':'); assert type(r) is str and r == ':x'
    6. parameter kind
      from inspect import signature
      r = tag_line('only'); p = signature(tag_line).parameters; assert type(r) is str and r == 'only' and p['separator'].kind.name == 'KEYWORD_ONLY' and p['tags'].kind.name == 'VAR_POSITIONAL'
      Why use join instead of repeated +=?

      join expresses the exact separator rule and builds the result in work proportional to the total text size for ordinary strings. The result requires space proportional to that size.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: a validated named limit

      Replace formatting with a bounded selection rule.

      The contract

      • Implement prefix(values, /, *, limit=2) for lists of integers and integer limits.
      • Return a new list of at most limit leading values, retaining order and duplicates; zero returns []; negative raises ValueError.
      • Do not mutate values, even when returning all items. Values must be positional and limit named.
      Transfer: a validated named limitPYTHON 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. default prefix
        r = prefix([4, 2, 4]); assert type(r) is list and r == [4, 2]
      2. empty
        p = []; r = prefix(p); assert type(r) is list and r == [] and r is not p
      3. zero
        r = prefix([1, 2], limit=0); assert type(r) is list and r == []
      4. large and preserved
        p = [3, 1, 3]; r = prefix(p, limit=10); assert type(r) is list and r == [3, 1, 3] and r is not p and p == [3, 1, 3]
      5. negative rejected
        r = prefix([2], limit=1); assert type(r) is list and r == [2]
        try:
            prefix([2], limit=-1)
        except ValueError:
            pass
        else:
            raise AssertionError('negative limit accepted')
      6. binding contract
        from inspect import signature
        p = signature(prefix).parameters; r = prefix([5], limit=1); assert type(r) is list and r == [5] and p['values'].kind.name == 'POSITIONAL_ONLY' and p['limit'].kind.name == 'KEYWORD_ONLY'
        What changed from tag formatting?

        The signature principles remain, but the body now validates a domain rule and owns a new shallow list. Copying k selected references takes O(k) time and space.

        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

        Compatibility is a contract

        A calling convention is part of compatibility: changing parameter order or a keyword name can break callers even when the arithmetic still works.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Maintain a small API without silently swapping shipping and service fees.

        Words you will see

        Compatibility
        Existing valid calls keep their intended meaning.
        Keyword name
        The public spelling callers use to bind a named argument.
        inspect.signature
        Standard-library inspection of a callable's reported parameters.

        Make the caller's assumptions visible

        quote(price, *, fee=0) requires price but names the extra amount. inspect.signature shows (price, *, fee=0). quote(10, fee=2) returns 12. Renaming fee to surcharge breaks that named call rather than translating it automatically.

        Reordering ordinary positional parameters can be worse: calls may still bind successfully but mean something else. Prefer adding optional keyword-only settings over inserting a new positional parameter into existing calls.

        Inspection helps, but does not prove behavior

        The displayed signature documents binding, not correctness of the body. Tests must still check that fee is added once, that defaults remain stable and that forbidden input is rejected where promised.

        Signature inspection is local standard-library work, supported by browser Python. It does not contact a service or inspect live production clients. A wrapper may report an original signature through metadata while executing a permissive *args, **kwargs body.

        The original example, step by step

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

        1. from inspect import signature

          Use local standard-library introspection.

        2. print(signature(quote))

          Show the keyword-only fee and its default.

        3. print(quote(10, fee=2))

          The named option contributes two to the price.

        Changing a positional parameter's order can silently change callers' meaning. Renaming a keyword parameter can break keyword callers. Add optional keyword-only parameters thoughtfully, and use signature inspection or a type checker to catch incompatible wrappers.

        Predict before you run

        Does signature(quote) run quote's arithmetic?

        Inspect a small public APIPYTHON 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 a breaking rename.

        Try: Rename fee to surcharge in the definition and body only.

        The signature changes, then the unchanged fee=2 call raises TypeError.

        Add a compatible option.

        Try: Add discount=0 after fee and subtract discount in the return expression.

        The old call still returns 12; the new named option is optional.

        Before you move on

        If fee is renamed to surcharge, will quote(10, fee=2) still work?

        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 raises TypeError because the keyword spelling is part of the call contract. Existing callers need a compatibility plan.

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

        Validation and ownership

        Binding checks how arguments arrive; validation checks whether their values meet a domain rule. Ownership states whether the function changes supplied objects.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A keyword-only limit can still be negative. Reject it explicitly and return a new slice rather than editing a caller's sequence.

        Words you will see

        Validation
        Checking a value against the promised rules.
        ValueError
        An exception for a value that violates a rule despite an acceptable kind of input.
        Shallow slice
        A new list whose entries still refer to the original element objects.

        Separate the two boundaries

        take(values, *, limit) requires a named limit. Its body then checks limit < 0 and raises ValueError for negatives. These are different failures: a positional limit is a TypeError at binding, while a named negative limit reaches validation.

        For limit=2, values[:limit] copies up to the first two entries into a new list. A limit beyond the length copies all entries. A zero limit produces an empty list. No source entry is removed.

        State what remains unsupported

        The example assumes a list and an integer limit; it does not parse a text limit or prohibit bool separately. If a stricter API needs type(limit) is int, add and test that rule rather than claiming annotations enforce it.

        The slice is shallow, not a recursive clone. Time and extra space are O(k) for k copied references, with k no larger than the input length. Shared nested entries still need a separate mutation policy.

        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 limit < 0:

          Check the domain rule after argument binding.

        2. return values[:limit]

          Return a fresh shallow prefix, not a destructive removal.

        3. print(values)

          The source still contains all three entries.

        A signature documents how inputs arrive but does not establish that their values are valid. Distinguish missing from explicitly None, validate business ranges and decide whether mutable inputs are borrowed or modified. Keep input parsing separate from the core transformation.

        Predict before you run

        What remains in values after the sample?

        Validate before selectingPYTHON 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 the range failure.

        Try: Use limit=-1 in the call.

        ValueError reports the invalid range; no plausible prefix is returned.

        Test a large boundary.

        Try: Use limit=20.

        The result contains all three entries and the source stays unchanged.

        Before you move on

        What should take([8, 9], limit=0) return, and what about limit=-1?

        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

        Zero returns a new empty list. A negative limit raises ValueError instead of applying Python's otherwise valid negative slice semantics.

        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.