declarative programming (static graph)

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

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


A new OP while_loop is highly recommended instead of While if the shape of parameter cond is [1]. OP while_loop is easier to use and is called with less code but does the same thing as While .

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

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


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())

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