ifelse

Contents

ifelse#

class brainpy.math.ifelse(conditions, branches, operands=None, show_code=False, dyn_vars=None, child_objs=None)[source]#

If-else control flows looks like native Pythonic programming.

Examples

>>> import brainpy.math as bm
>>> def f(a):
>>>    return bm.ifelse(conditions=[a > 10, a > 5, a > 2, a > 0],
>>>                     branches=[lambda: 1,
>>>                               lambda: 2,
>>>                               lambda: 3,
>>>                               lambda: 4,
>>>                               lambda: 5])
>>> f(1)
4
>>> # or, it can be expressed as:
>>> def f(a):
>>>   return bm.ifelse(conditions=[a > 10, a > 5, a > 2, a > 0],
>>>                    branches=[1, 2, 3, 4, 5])
>>> f(3)
3
Parameters:
  • conditions (bool, sequence of bool) – The boolean conditions.

  • branches (Any) – The branches, at least has two elements. Elements can be functions, arrays, or numbers. The number of branches and conditions has the relationship of len(branches) == len(conditions) + 1. Each branch should receive one arguement for operands.

  • operands (optional, Any) – The operands for each branch.

  • show_code (bool) – Whether show the formatted code.

  • dyn_vars (Variable, sequence of Variable, dict) –

    The dynamically changed variables.

    Deprecated since version 2.4.0: No longer need to provide dyn_vars. This function is capable of automatically collecting the dynamical variables used in the target func.

  • child_objs (optional, dict, sequence of BrainPyObject, BrainPyObject) –

    The children objects used in the target function.

    Deprecated since version 2.4.0: No longer need to provide dyn_vars. This function is capable of automatically collecting the dynamical variables used in the target func.

Returns:

res – The results of the control flow.

Return type:

Any