---
author: Nathan Carter (ncarter@bentley.edu)
---

This answer assumes you have imported SymPy as follows.


```python
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output
```

SymPy has support for piecewise functions built in, using `Piecewise`.
The function above would be written as follows.


```python
var( 'x' )
formula = Piecewise( (x**2, x>2), (1+x, x<=2) )
formula
```




$\displaystyle \begin{cases} x^{2} & \text{for}\: x > 2 \\x + 1 & \text{otherwise} \end{cases}$



We can test to be sure the function works correctly by plugging in a few
$x$ values and ensuring the correct $y$ values result.
Here we're using the method from how to substitute a value for a symbolic variable.


```python
formula.subs(x,1), formula.subs(x,2), formula.subs(x,3)
```




$\displaystyle \left( 2, \  3, \  9\right)$



For $x=1$ we got $1+1=2$.  For $x=2$ we got $2+1=3$.  For $x=3$, we got $3^2=9$.

31ceec111060cb3f4e5cc4b8201b7ae6e6981c70
ipynb
Jupyter Notebook
database/tasks/How to write a piecewise-defined function/Python, using SymPy.ipynb
nathancarter/how2data
7d4f2838661f7ce98deb1b8081470cec5671b03a
MIT
database/tasks/How to write a piecewise-defined function/Python, using SymPy.ipynb
nathancarter/how2data
7d4f2838661f7ce98deb1b8081470cec5671b03a
MIT
database/tasks/How to write a piecewise-defined function/Python, using SymPy.ipynb
nathancarter/how2data
7d4f2838661f7ce98deb1b8081470cec5671b03a
MIT
2021-07-18T19:01:29.000Z
2022-03-29T06:47:11.000Z
Qwen/Qwen-72B
1. YES
2. YES