.. _how_to_while_loop:

How to write a while loop?
==========================

.. tbinit:: howto_whileloop

A while loop consists of a branch, and a condition task inside this branch, which determines whether one revisits the branch again.

One needs to define the branch with ``loop=True``, and then make sure that there if one ``_if`` decorator, with a jump back to the branch itself.

We begin from empty repo.

.. tbshellcommand:: tb init

Here is the simplest example workflow. Create a following ``workflow.py``

.. tbfile:: workflow.py

.. literalinclude:: workflow.py

and a following ``tasks.py``

.. tbfile:: tasks.py

.. literalinclude:: tasks.py

This is the absolutely simplest example of workflow. The Phi-operator argument default refers to
initialization of the while loop, i.e. on the first iteration, we get the input to the iterate task
from the workflow input ``self.number``. On the next step, we are coming from ``entry``-branch,
and thus we will refer to the previous result of the iterate.

We can iterate the workflow few times and observe the results

.. tbshellcommand:: tb workflow workflow.py && tb run . >/dev/null && tb ls --sort=topo -c sirITfo
.. tbshellcommand:: tb workflow workflow.py && tb run . >/dev/null && tb ls --sort=topo -c sirITfo
.. tbshellcommand:: tb workflow workflow.py && tb run . >/dev/null && tb ls --sort=topo -c sirITfo

.. tbfile:: ../../tutorial/dynamical_workflows/converging_style.json
.. tbhiddenshellcommand:: tb view-workflow -s converging_style.json -f workflow.py -o while_loop_workflow.html WhileLoopWorkflow
.. tbviewworkflow:: while_loop_workflow.html

To view an experimental automatically generated workflow diagram of the workflow here, click :download:`here <../../_static/while_loop_workflow.html>`.

This structure is the simplest for loop. However, to make the initialization and finalization of while loop more clear,
and usable, see How to write a practical while loop How to.
