You can use a ufl conditional (loaded with from ufl import conditional, following the documentation:
Conditional Operators
Conditional
UFL has limited support for branching, but for some PDEs it is needed. The expression c in:
c = conditional(condition, true_value, false_value)
evaluates to true_value at run-time if condition evaluates to true, or to false_value otherwise.
This corresponds to the C++ syntax (condition ? true_value: false_value) , or the Python syntax (true_value if condition else false_value) .