while_loop

api_attr

declarative programming (static graph)

paddle.fluid.layers.while_loop(cond, body, loop_vars, is_test=False, name=None)[source]

while_loop is one of the control flows. Repeats while_loop body until cond returns False.

Parameters
  • cond (Callable) – A callable returning a boolean tensor controlling whether to continue looping. And cond takes as many arguments as loop_vars .

  • body (Callable) – A callable returning a tuple or list of tensors or LoDTensorArrays of the same arity (length and structure) and types as loops_vars . And body takes as many arguments as loop_vars .

  • loop_vars (list|tuple) – A list or tuple of tensors or LoDTensorArrays that is passed to both cond and body .

  • is_test (bool, optional) – A flag indicating whether execution is in test phase. Default value is False.

  • name (str, optional) – Normally there is no need for users to set this property. For more information, please refer to Name. Default is None.

Returns

A list or tuple of tensors or LoDTensorArrays which returned by body .

Returen type:

list(Variable)|tuple(Variable).

Raises
  • TypeError – If the type of cond is not callable.

  • TypeError – If the type of body is not callable.

  • TypeError – If the type of loop_vars is not list or tuple.

  • TypeError – If the type of cond returns is not Variable.

  • TypeError – If the type of cond returns is not a boolean variable.

  • TypeError – If the shape of cond returns is not equals 1.

  • ValueError – If the var_loops is empty.

  • ValueError – If the length or type of body returns is not same as loop_vars.

Examples

import paddle.fluid as fluid
import paddle.fluid.layers as layers

def cond(i, ten):
    return i < ten

def body(i, ten):
    i = i + 1
    return [i, ten]

main_program = fluid.default_main_program()
startup_program = fluid.default_startup_program()
with fluid.program_guard(main_program, startup_program):
    i = layers.fill_constant(shape=[1], dtype='int64', value=0)     # loop counter
    ten = layers.fill_constant(shape=[1], dtype='int64', value=10)  # loop length
    i, ten = layers.while_loop(cond, body, [i, ten])

    exe = fluid.Executor(fluid.CPUPlace())
    res = exe.run(main_program, feed={}, fetch_list=[i])
    print(res) # [array([10])]