You can use a conditional, see:
https://fenics.readthedocs.io/projects/ufl/en/latest/manual/form_language.html?highlight=Conditional%20#conditional
and