While

class paddle.fluid.layers.While(cond, is_test=False, name=None)[source]

while loop control flow. Repeat while body until cond is False.

Parameters
  • cond (Variable) – A Tensor whose data type is bool controlling whether to continue looping.

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

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

Examples

import paddle.fluid as fluid
import numpy as np

i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)           # loop counter

loop_len = fluid.layers.fill_constant(shape=[1],dtype='int64', value=10)    # loop length

cond = fluid.layers.less_than(x=i, y=loop_len)
while_op = fluid.layers.While(cond=cond)
with while_op.block():
    i = fluid.layers.increment(x=i, value=1, in_place=True)
    fluid.layers.less_than(x=i, y=loop_len, cond=cond)

exe = fluid.Executor(fluid.CPUPlace())
exe.run(fluid.default_startup_program())

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