Work with functionsLesson 22 of 48 · 7 min
Define a piecewise rule
Build Piecewise with an explicit boundary and fallback branch.
Maths refresher: Rules on regions
A piecewise definition states both the formula and the region where it applies. Boundary inclusion is part of the rule.
At -2 use the first branch and obtain 2. At 0 use the second branch and obtain 0.
A piecewise function uses different formulas in different regions. Conditions are evaluated in order, and the first applicable branch wins. A final True condition provides an otherwise branch.
The absolute-value example has a negative-input branch and a nonnegative fallback. The point falls in the fallback because the first condition is strict. Writing that boundary deliberately avoids gaps or double interpretations.
Piecewise can represent tariffs, thresholds and physical regimes, but the model must state the permitted inputs and any discontinuities. Inspect representative interior points and exact boundaries before differentiating, integrating or converting the rule into numerical code.
Which branch handles when the first condition is ?
Write a prediction (optional)
Exact symbolic investigation
Select Run Python with the code unchanged.
Your saved draft is open. To use the published code, select Restore example in Tools. Use Recover draft to bring back your code.
Tools
About Python
Python and the course packages can load while you read. Each run starts with fresh user variables; imported modules stay loaded. Stop replaces the worker. Runtime details ↗
Ctrl+Enter or ⌘+Enter runs Python.
Execution error
Technical error details
Your result
Python text output
Compare with the worked example
Executed from the published Python during the site build. Your own run appears above. Build environment ↗
Worked text output
Piecewise rule: Piecewise((-x, x < 0), (x, True)) Inputs and values: [(-2, 2), (0, 0), (2, 2)]
Read the starter result
Read Inputs and values as pairs of an input and its result. At 0 the strict first condition is false, so the fallback supplies 0. The rule gives the magnitude of every real input.
Edit and compare
Replace rule = sp.Piecewise((-x,x<0),(x,True)) with rule = sp.Piecewise((5,x<20),(0,True)). Replace inputs = [-2,0,2] with inputs = [19,20,21]. Select Run Python and use Inputs and values to identify the charge at exactly 20.
Scope. A piecewise rule needs its own domain and boundary checks; a symbolic definition alone does not validate a real tariff or regime change.
Try a fresh case
Two Piecewise conditions both match an input. Which branch is selected?
Need a hint?
Hint 1
Read Piecewise from top to bottom.
Hint 2
Stop at the first true condition.