Errors are part of the contract
Validate boundaries and handle only failures you understand.
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: 12 minutes; optional deep dive: 8 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.
- Read traceback causes
- Catch specific exceptions
- Avoid silent fallbacks
Wrong input is not the same as a broken program
An exception reports that an operation could not complete its contract. Its type names the kind of failure; a traceback shows the calls that led there.
Understand first
A program must distinguish an unusable input from a programming mistake. Otherwise a failed conversion may become a plausible-looking result. Begin with function calls and integer conversion; no filesystem or network failure is needed to study exceptions.
Words you will see
- Exception type
- The class describing a failure category, such as ValueError.
- Traceback
- The sequence of calls and source locations leading to an unhandled exception.
- Propagate
- Let a failure travel back to a caller rather than handling it here.
Read the failure from operation to caller
int('tea') receives a string, which is an allowed kind of argument, but its contents cannot represent an integer. It raises ValueError. int(None) instead raises TypeError because the argument is not an accepted type for this conversion. The distinction helps a caller choose what it can reasonably recover from.
The except clause matches ValueError and binds the exception to error. It displays the class name and an explanation, not a converted number. If the handler were absent, the runner would show a traceback. Read the last exception type/message first, then locate your own failing operation and follow the calling frames.
A handler changes control flow
After the raise, convert does not return a value to the interrupted call. The matching handler runs, then execution continues after the try/except statement. A handler is not a request to resume at the next line inside convert.
Use a condition for ordinary expected branching when it expresses the rule clearly, and exceptions for an operation's documented failure. Do not remove the traceback from an unknown bug just to make output look clean. This in-memory fixture intentionally catches one expected failure; all other exception types remain visible to the shared runner.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def convert(text):Define a conversion that can fail.
return int(text)Return an int only if conversion succeeds.
convert("tea")Attempt an invalid numeric value.
except ValueError as error:Handle exactly the conversion's value failure.
print(type(error).__name__)Display ValueError without depending on version-specific message wording.
print("Input was not integer text")Explain the rejected input, not a successful numeric result.
A ValueError can mean an input could not be converted; a TypeError often means an unsupported operation/type. Tracebacks show the call chain and the failing operation. Read the final exception message, then follow your code frames.
Conceptual error propagation for the original conversion
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Callerconvert('tea') requests an integer.
- Operationint raises ValueError instead of returning a number.
- Unwindconvert cannot complete its return.
- Matching handlerThe caller's ValueError handler explains the failure; TypeError would propagate.
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.
Take the successful branch.
Try: Replace "tea" with "12" and change convert("12") to print(convert("12")).
It prints 12 and neither handler print runs.
Observe an unmatched failure.
Try: Replace convert("tea") with convert(None).
TypeError propagates visibly; ValueError is not a universal catch-all.
Before you move on
If convert(None) replaces convert('tea'), will this handler print the same explanation?
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. int(None) raises TypeError, which this ValueError handler does not catch. The runner must show that failure rather than pretend conversion succeeded.
Catch narrowly at a useful boundary
A narrow handler covers only the operation whose failure you understand. Conversion and domain validation are separate stages with separate reasons to reject input.
Understand first
A count of minus one is numeric but invalid for this application. Keeping int conversion separate from the range rule lets callers receive an accurate explanation instead of the wrong error label.
Words you will see
- try suite
- The indented operations watched by a following handler.
- Domain validation
- Checking a value against the application's rules after basic conversion.
- from None
- An explicit choice to suppress displayed implicit exception context when raising a replacement error.
Handle the expected operation only
The try suite contains int(text), not the entire function. If conversion raises ValueError, the handler raises a clearer whole-number message. A successful conversion skips the handler and reaches the count < 0 check. That check rejects a negative integer with its own message, not a conversion message.
The original contract demonstrated here accepts text and uses int's parsing rules, including surrounding whitespace and signs. It does not claim that every possible input type is accepted. TypeError remains visible for an invalid argument type. If callers need a stricter ASCII-only format, validate that separately before conversion.
Decide how much cause information to retain
from None simplifies this expected user-facing conversion report. It does not mean the underlying failure never happened. In internal diagnostics, raise ... from error often gives better causal information; optional depth demonstrates that choice.
Placing a logging call, dictionary lookup and conversion in one broad try makes it unclear which operation failed. Narrow suites reduce accidental recovery from unrelated bugs. Use an ordinary if for the negative rule because a comparison states it directly; there is no need to manufacture an exception just to select a normal branch.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
count = int(text)Convert text within the focused try suite.
except ValueError:Handle only a numeric-format failure.
raise ValueError("Count must be a whole number") from NoneReplace the displayed conversion explanation deliberately.
if count < 0:Check the separate nonnegative domain rule after successful conversion.
raise ValueError("Count cannot be negative")Reject a numeric value outside the domain.
return countReturn only a validated count.
print(parse_count("12"))Print 12 from the valid path.
Keep the try block focused on the operation you expect to fail. Catching Exception around an entire program can hide bugs and turn failures into plausible-looking data.
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 a domain failure.
Try: Change parse_count("12") to parse_count("-2").
The negative-count error appears, not the format error.
Check a format failure.
Try: Use parse_count("twelve").
The whole-number error appears; no count is returned.
Before you move on
Which error should '-2' produce, and why is it not the whole-number message?
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
Count cannot be negative. int('-2') succeeds, so conversion's handler is skipped and domain validation rejects the resulting integer.
A fallback must mean something
A fallback is a documented replacement for one expected absence or failure. It must not turn every possible bug into a believable value.
Understand first
An optional field can reasonably default to zero when it is absent. A supplied but malformed count is different evidence and should not quietly enter a total. Use None as a deliberate absence marker, not generic falsiness.
Words you will see
- Sentinel
- A distinguished value that represents a special state; None means absent here.
- Fallback
- An agreed substitute value used for a particular documented condition.
- Silent corruption
- A believable result that hides a failure and is therefore harder to detect.
Separate absent, zero and malformed
The identity comparison text is None matches only absence. That branch returns zero immediately. The string '0' instead reaches int and independently produces the valid number zero. The same final number can have two legitimate causes, but that does not make all other inputs equivalent.
'tea' is supplied information with the wrong format. Its ValueError propagates to the demonstration handler, which prints invalid instead of a numeric substitute. Empty text is also supplied but malformed. Replacing the None comparison with if not text would quietly turn that malformed empty string into the absent case.
Choose recovery at the caller's boundary
A caller may ask for corrected input, reject the record or display a diagnostic. Those actions have more meaning than returning zero from an indiscriminate except. If the product requires distinguishing an omitted count from an explicit zero later, return a separate status or preserve None instead of collapsing the states.
This function intentionally does not enforce nonnegative values; its purpose is absence handling, not the earlier count contract. Reuse parse_count instead of int if the nonnegative rule also applies. Recovery decisions should compose explicit contracts rather than silently importing assumptions from a nearby example.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if text is None:Test absence specifically.
return 0Use the documented default only in that branch.
return int(text)Convert any supplied text or propagate its failure.
print(optional_count(None))Display the absence default.
print(optional_count("0"))Display a successfully parsed zero.
optional_count("tea")Trigger the expected malformed-input failure.
except ValueError:Let the caller handle the failure explicitly.
Returning zero on every error can silently corrupt a calculation. Either choose a documented default for an expected absence or propagate an error that the caller can act on.
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 empty supplied text.
Try: Replace optional_count("tea") with optional_count("").
The invalid message remains; empty text is not the absence sentinel.
Observe the intentionally different domain contract.
Try: Add print(optional_count("-2")).
It prints -2. This example handles absence and conversion, not nonnegative validation.
Before you move on
Should optional_count('') default to zero under this precise contract?
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. Only None means absent. Empty supplied text reaches int and raises ValueError, so the caller can ask for a correction.
Where this idea earns its place
An error contract should distinguish an expected invalid input from an unavailable dependency or a programming defect. Returning a plausible default for every failure makes these states indistinguishable and can corrupt downstream decisions. Begin by naming which failures a caller can correct and which must propagate for investigation.
Follow the mechanism step by step
When an exception is raised, Python unwinds execution until a matching handler is found. The handler's placement determines how much work is abandoned. A narrow try around int(text) can translate a conversion error without accidentally catching a bug in later aggregation or output code.
Work through a concrete application
Parse a count, then validate its domain range as a separate step. Give the user a safe message describing the accepted shape. If translating an underlying exception, preserve its cause when useful rather than discarding all diagnostic context. Use context managers or finally for resources that must be released regardless of the result.
Failure cases and misleading shortcuts
except Exception around a whole service can hide AttributeError, driver faults and other defects under the same fallback. Catching BaseException can interfere with cancellation or interpreter-exit signals. Validation by assert is also unsuitable for required runtime checks because optimization can remove assertions.
Cost, ownership and alternatives
Validation should bound work before expensive processing, including payload size, shape and allowed values. Error reporting itself needs limits: retaining every invalid input in a large batch can consume memory and leak sensitive data. Select safe identifiers and a bounded sample while preserving an accurate total failure count.
Verify the contract
Test the specific exception type and the caller-visible error contract. Include wrong types, empty values, malformed representations and boundary values. Inject an unrelated programming failure and confirm it is not silently converted into a normal result. Verify cleanup on both the expected validation path and an unexpected failure.
Transfer question: When is an empty result an acceptable fallback?
Only when the documented domain meaning of the expected condition is genuinely empty and the caller can rely on that contract. A database outage is not an empty query result, and a malformed import is not a successfully processed file containing no records.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Validate a percentage
Accept integers from 0 to 100 inclusive. Raise ValueError outside that range.
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 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.
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: enforce the percentage boundary
Return valid percentages and distinguish wrong types from wrong values.
The contract
- Input may be any object. Accept only exact int values from 0 to 100 inclusive; bool is not an accepted int.
- Return the original accepted integer. Wrong type raises TypeError; out-of-range int raises ValueError. No coercion, fallback or mutation.
- Each call is independent, browser-local and side-effect free. There is no ordering or deduplication operation.
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.
- ordinary
assert checked_percentage(42) == 42
- zero
assert checked_percentage(0) == 0
- hundred
assert checked_percentage(100) == 100
- outside
for value in (-1, 101): try: checked_percentage(value) except ValueError: continue raise AssertionError("Out-of-range int accepted") - wrong type and absence
for value in (True, False, None, "20", 20.0): try: checked_percentage(value) except TypeError: continue raise AssertionError("Wrong type accepted") - ownership and repeated calls
value = [20] try: checked_percentage(value) except TypeError: assert value == [20] else: raise AssertionError("Mutable input accepted") assert checked_percentage(25) == 25 and checked_percentage(25) == 25
Why check type before range?
It ensures a deliberate TypeError instead of an accidental comparison failure and rejects numerically equal floats/bools. A fixed number of type and bound checks uses O(1) control steps and extra references, ignoring arbitrary-integer comparison bit costs.
Guided: preserve absence as a status
Keep omitted input distinguishable from explicit zero rather than collapsing both into one number.
The contract
- Input is None or a str; other types raise TypeError. None returns the tuple ('absent', None).
- For strings, use int's base-ten conversion. Negative results or malformed strings raise ValueError. Return ('present', count) for accepted nonnegative values, including zero.
- No mutation, I/O or retained state. Repeated calls do not depend on prior errors; whitespace and a leading plus are accepted by int.
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.
- present
assert count_status("12") == ("present", 12) - absence
assert count_status(None) == ("absent", None) - zero
assert count_status("0") == ("present", 0) - conversion rules
assert count_status(" +02 ") == ("present", 2) - invalid supplied
for text in ("", "tea", "-1"): try: count_status(text) except ValueError: continue raise AssertionError("Malformed or negative supplied text accepted") - type ownership and independence
value = [] try: count_status(value) except TypeError: assert value == [] else: raise AssertionError("Non-text accepted") assert count_status(None) == ("absent", None) and count_status("3") == ("present", 3) and count_status("3") == ("present", 3)
Why return a status when count is None for absence?
The named status makes the domain distinction explicit and can grow into richer result handling. Conversion scans the text; for d digits, storage includes the resulting integer, and very large integer conversion has more than constant cost and interpreter safety limits.
Transfer: collect expected row failures
Change from fail-fast parsing to a documented partial-result contract.
The contract
- Input is a list of strings. Convert each with int and reject negative results. Keep accepted ints, including repeats and zero, in input order.
- Return a fresh tuple (values, bad_positions), each containing a fresh list. Positions are zero-based source indices for malformed or negative strings, not compacted indices. Empty input returns ([], []).
- Only ValueError from conversion/domain is classified as a bad row; unsupported non-string objects whose int conversion raises TypeError must propagate TypeError. Never mutate input or retain lists between calls. No I/O.
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.
- mixed
assert collect_counts(["2","tea","-1","3"]) == ([2,3], [1,2])
- empty ownership
a = collect_counts([]) b = collect_counts([]) assert a == ([],[]) and b == a and a[0] is not a[1] and a[0] is not b[0] and a[1] is not b[1]
- zero and repeats
assert collect_counts(["0","2","2"]) == ([0,2,2],[])
- source positions
assert collect_counts(["bad","1","bad","2","bad"]) == ([1,2],[0,2,4])
- unexpected type
try: collect_counts([None]) except TypeError: pass else: raise AssertionError("Unexpected TypeError was swallowed") - ownership and isolation
rows = ["3","bad"] a = collect_counts(rows) a[0].append(99) assert a == ([3,99],[1]) and rows == ["3","bad"] and collect_counts(rows) == ([3],[1])
Why is this partial-result policy acceptable where an audited total rejected all errors?
The result explicitly includes rejected positions; the caller can decide what incomplete data means. For n rows, traversal is O(n) plus conversion work over their text, with O(n) output space in the worst case.
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 milestonePreserve causes and clean resources
Exception chaining records why a higher-level operation failed. Cleanup runs as control leaves a scope, but it does not turn a failed operation into a successful one.
Understand first
A report service may expose a report-level error while preserving the original conversion cause for debugging. Separately, a cleanup scope should release resources on successful return and on propagation. These are control-flow promises, not interchangeable recovery techniques.
Words you will see
- Cause
- An explicitly linked underlying exception stored in __cause__.
- finally
- A suite run as a try statement exits through normal or exceptional control flow.
- Translation
- Raising a higher-level exception to express the caller-facing operation that failed.
Translate without erasing evidence
int('tea') raises ValueError. The except clause binds it as error, then raises RuntimeError with an explicit cause. The caller handles the higher-level RuntimeError and can still inspect ValueError as its cause. In an unhandled traceback, Python displays both linked failures.
Unlike from None, from error keeps the cause visible. Choose a user-facing summary for clarity while retaining diagnostics for investigation. Do not expose secrets in exception text: the chain is useful evidence, not permission to log private input indiscriminately.
Cleanup is not a substitute result
finally prints cleanup before the exception reaches the caller. A successful return also passes through finally. Prefer with for a resource whose context manager already defines correct cleanup, as shown for streams earlier. A finally block is useful for a custom cleanup obligation not already expressed by a context manager.
Do not return from finally: it can override a pending return or suppress an exception. Cleanup itself can fail and mask the earlier error, so production cleanup needs a deliberate error policy. This fixture prints a marker only; it does not claim to close a real file or roll back a write.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return int(text)Attempt the lower-level conversion.
except ValueError as error:Capture its known value failure.
raise RuntimeError("Report rejected") from errorRaise a report-level failure with the original as cause.
finally:Enter exit work during propagation.
print("cleanup")Display the marker before the caller handler.
except RuntimeError as error:Handle the translated failure.
print(type(error.__cause__).__name__)Confirm the linked cause is ValueError.
Use raise NewError(...) from error to preserve causal context when translating exceptions. finally runs cleanup whether or not an exception occurs; a with context is preferable for managed resources.
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.
Observe cleanup during success.
Try: Replace the outer read_count("tea") call with print(read_count("8")).
It prints cleanup then 8. The caller's handler is skipped.
Compare deliberate context suppression.
Try: Replace from error with from None.
The final cause display becomes NoneType, illustrating that an explicit cause is no longer retained there.
Before you move on
If the function converts '8' successfully, does finally still 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
Yes. Cleanup runs before the successful return reaches its caller. The exception translation branch is skipped, so no chained error is created.
Validation at trust boundaries
Boundary validation establishes runtime facts about incoming values. A type annotation describes an intended interface but does not enforce it when the function runs.
Understand first
User data can bypass static checking and annotated interfaces. Validate at the entry point before sorting, arithmetic or persistence makes a wrong value harder to diagnose. The chosen rule here is an exact integer percentage, including zero and one hundred.
Words you will see
- Annotation
- A type description attached to a name or function interface; Python does not automatically validate calls against it.
- Inclusive bound
- A range endpoint that is allowed.
- Short-circuit
- Evaluation that stops once the condition's outcome is determined.
Type first, then value
The exact type check rejects bool even though bool is a subclass of int. It also rejects strings, None and floats before numeric comparisons happen. The chained comparison 0 <= value <= 100 then states both inclusive limits. TypeError and ValueError distinguish a wrong representation from an out-of-range integer.
Some APIs accept any numeric value or coerce text deliberately. That is another valid contract, but it needs rules for fractions, booleans and non-finite numbers. Do not broaden this one accidentally by converting everything with int; 3.8 would be silently truncated.
Keep validation close to incoming data
After validation, internal calculation code can rely on the established rule within that call. Rechecking every intermediate value may obscure intent, while never checking external data is unsafe. Nested reports need shape checks from outside inward and size limits before expensive processing.
An if and explicit raise are appropriate for production rejection. An assert can be removed under optimisation and is not an input firewall. This program is deterministic and browser-local: it demonstrates data validation, not authentication, permissions, a secure upload service or a host process.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def percentage(value: int) -> int:Describe the intended interface without claiming automatic enforcement.
if type(value) is not int:Require an exact int, excluding True.
if not 0 <= value <= 100:Reject integers outside both inclusive endpoints.
return valueReturn only an established percentage.
print(percentage(0), percentage(100))Show both accepted boundaries.
percentage(True)Exercise the wrong-type path.
except TypeError:Report the deliberately rejected boolean.
Type annotations do not validate incoming JSON or user text. Check size, shape and allowed values before acting. Avoid exception-driven loops for ordinary cases when a simple condition communicates intent.
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.
Cross the upper bound.
Try: Replace percentage(True) with percentage(101) and catch ValueError instead.
The out-of-range handler runs for an integer of the right type but wrong value.
Keep type distinct from value.
Try: Use percentage(100.0) in the original TypeError demonstration.
The float is rejected even though it compares equal to 100.
Before you move on
Would percentage(100.0) pass because its numeric value equals 100?
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. Its exact type is float, so TypeError occurs before the range check. Representation is part of this interface, not just numerical equality.
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.
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.