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

Static Graph

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


Local variables defined in body cannot be obtained through fetch_list of Executor , variables should be defined outside body and placed in loop_vars for looping, then these variables can be fetched by fetch_list .

  • 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.


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


>>> import paddle
>>> paddle.enable_static()

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

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

>>> main_program = paddle.static.default_main_program()
>>> startup_program = paddle.static.default_startup_program()
>>> with paddle.static.program_guard(main_program, startup_program):
...     i = paddle.full(shape=[1], fill_value=0, dtype='int64')     # loop counter
...     ten = paddle.full(shape=[1], fill_value=10, dtype='int64')  # loop length
...     i, ten = paddle.static.nn.while_loop(cond, body, [i, ten])

...     exe = paddle.static.Executor(paddle.CPUPlace())
...     res = exe.run(main_program, feed={}, fetch_list=[i])
...     print(res)
[array([10], dtype=int64)]