if_else#

ivy.if_else(cond, body_fn, orelse_fn, vars)[source]#

Take a boolean condition and two functions as input. If the condition is True, the first function is executed and its result is returned. Otherwise, the second function is executed and its result is returned.

Parameters:
  • cond (bool) – A boolean value representing the condition to be evaluated.

  • body_fn (Callable) – A callable function to be executed if the condition is True.

  • orelse_fn (Callable) – A callable function to be executed if the condition is False.

  • vars (Iterable[Union[Array, NativeArray]]) – Additional variables to be passed to the functions.

Return type:

Any

Returns:

ret – The result of executing either body_fn or orelse_fn depending on the value of cond.

Examples

>>> cond = True
>>> body_fn = lambda x: x + 1
>>> orelse_fn = lambda x: x - 1
>>> vars = (1,)
>>> result = ivy.if_else(cond, body_fn, orelse_fn, vars)
>>> print(result)
2
>>> cond = False
>>> body_fn = lambda x: x * 2
>>> orelse_fn = lambda x: x / 2
>>> vars = ivy.array([1, 2, 3])
>>> result = ivy.if_else(cond, body_fn, orelse_fn, vars=(vars,))
>>> print(result)
ivy.array([0.5, 1.0, 1.5])