A new OP :ref:`api_fluid_layers_while_loop` is highly recommended instead of ``While`` if the shape of parameter ``cond`` is [1].
OP :ref:`api_fluid_layers_while_loop` is easier to use and is called with less code but does the same thing as ``While`` .
Notice:
Local variables created in ``While`` are similar to that created in while of C++, and cannot be referenced externally.
As a result, they cannot be obtained through ``fetch_list`` of ``Executor``. If you would like to access the variable
out of ``while`` , PaddlePaddle provides ``assign`` API to assign local variables to external. Please refer to example
code 2 or refer to `issue#22724 <https://github.com/PaddlePaddle/Paddle/issues/22724>`_.
Args:
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 :ref:`api_guide_Name` .
one = fluid.layers.fill_constant(shape=[1], dtype='float32', value=1)
data = fluid.data(name='data', shape=[1], dtype='float32')
sums = fluid.layers.fill_constant(shape=[1], dtype='float32', value=0) # Define the variable to be obtained ouside of While, which name should be different from the variable inside the While to be obtained
fluid.layers.assign(sums_tensor, sums) # Update the value of sums_tensor defined in While to the sums which defined outside of While through layers.assign
i = fluid.layers.increment(x=i, value=1, in_place=True)
data = fluid.layers.elementwise_add(x=data, y=one)