Do while loop in Python

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Introduction to Do While Loop in Python

A do-while loop is referred to as an “exit controlled” loop since the looping condition (or predicate) is checked after the code block wrapped inside the do-while loop is executed once. In contrast, for-loop and while-loop are entry controlled loops. That is, the condition for looping is checked before the code-block in the loop is executed even once.

In short, the do-while loop executes at least once, irrespective of whether its looping condition is true, while for loop and while loop is not executed in a similar case.

One of the important examples where this loop is used is in menu-driven programs, where the menu must be shown to the user at least once, and every time they return to the menu screen.

This article will explain the code and the logic for implementing the do-while loop in Python. Since Python does not explicitly provide its do-while loop (like C and C++ do), we will have to make a workaround using the existing loops in Python, for-loop, and while-loop. But first, let us look at the control flow for the do-while loop.

Flow Chart of A Do While Loop

A do-while loop in a logic flow diagram (or a flow chart), looks as follows:

Flowchart for Do While Loop in Python

Explanation of flow diagram:

The control of the program enters the start of the loop. The code wrapped within the do-while loop is executed for the first time, and then after its complete execution, the control goes on to check the looping condition.

Suppose the looping condition evaluates to true, and the control shifts to the start of the code block (and its execution begins again). If the condition evaluates to a false value, the control exits the loop, and the code block is no longer executed.

If reading code helps you understand better, here is a C/C++ style code that should help you understand how the do-while loop should execute.

As you can see from the code sample and the flowchart, the condition for the loop is checked after executing the wrapped code at least once.

Since such a construct is not present in Python by default, we can modify the existing loops to function logically like the do-while loops in other languages.

Emulating A Do While Loop In Python

Let us build the solution logically by listing what all our code needs to do:

  1. Enter a code scope irrespective of the looping condition
  2. Execute the code block
  3. Check the looping condition
  4. Repeat until the looping condition becomes false

Seeing the 4th point, we understand we will have to use some looping mechanism. We need what is called an infinite-loop, which provides an unconditional infinite loop and, consequently, allows us to enter the code block without any restriction for the first time. Python, by default, provides two loops, the for-loop and the while loop. And you know what? We can implement a do-while loop in Python using both of them! Let's see them one by one.

1. Using a For Loop to emulate the Do-while loop in Python

Beginners in Python must have used the for loop over some range, or some list, dictionaries, using some iterable. Now we will use what is referred to as an iterator (since it provides a procedure to implement infinite loops). For implementing the same, we call another method, iter().

The syntax for using the iter method to solve our problem is:

Where data_type can be any class, while the arg argument can be any object of any class but not equal to the object returned by that class’ default constructor.

The following table shows the various data_types vs. the various possible arg, which will allow us to emulate an infinite loop.

int1, -2, 1.4, ‘v’, “a random string”, [1,3,4] (anything other than 0)
float1, 0.1, 0.001, -3, (anything other than 0 or 0.0)
dictAnything other than {}
listAnything other than []
tupleAnything other than ()
strAnything other than ‘’

Readers are free to explore more such data_type and arg pairs. But for the sake of simplicity, we will use and suggest the following code snippet for emulating a do-while loop in Python using a for loop.

Or equivalently

Explanation:

  1. The control enters the for loop. After every execution, the loop will try to check if the looping variable (_), which was initially 0 (because 0 is the value returned by constructor int()), has been able to become equal to the value of the second parameter, that is 1. Since we make no changes to the iterating variable _ inside the code block, it never becomes equal to 1, and therefore, we get an infinite loop.

  2. While executing the code block inside the loop block, if the condition is evaluated to be true, then nothing will happen. The execution will continue to the next iteration. Otherwise, the control will break out of the loop.

Therefore, the syntax for implementing the do while loop in Python using for loop is:

Or

2. Using a While Loop

It is much simpler than implementing an infinite loop using for loop in Python. The general structure of a while loop in Python is given below:

Now, if we want to enter the while loop unconditionally, we can give it a true value forever. Can you guess what such a value can be? Well, the boolean True itself!

Now, this has become an infinite loop that will execute unbounded. But we want a condition check, don’t we? So, just like we did above in for loop implementation, we add an if-else block to check the looping condition and break out of the loop if the condition is not met.

Or equivalently

Therefore, the syntax for implementing a do-while loop in Python using while loop is:

Or equivalently

So we’ve got our theory as well as our implementation cleared out. Let’s summarize these code snippets and move along further to view some examples.

Example

Output:

Explanation:

The control enters the beginning of the loop and evaluates the predicate given in front of while. Since it is true by default, the control enters the code block and executes statements present inside.

Variable i is incremented, and it becomes 11. Further, since the condition (11<10) evaluates to false, the control breaks out of the loop.

An interesting thing to notice is that the code executes at least once even though our looping condition requires that i < 10.

Similar code using the for loop implementation:

Output:

Explanation:

Before entering the loop block, variable i is set to 10. The control arrives at the loop block, and since _ is not equal to 1 (as it is equal to 0), the control enters the loop block and executes the statements in it. Since i is equal to 10, the condition i>=10 is considered true, and the control breaks out of the loop block.

Let’s see one more example of printing the first ten multiples of 2 using both implementations.

Ouput:

Equivalently:

Output

The explanation for these two programs is similar to the code samples above.

Readers are implored to implement more such programs using these code snippets to make their use more handy and justifiable.

Conclusion

The article can be summarized as follows:

  1. The structure of execution of the do-while loop in Python was
  2. Since Python doesn’t have an in-built do-while loop, we implemented the do-while loop in Python using for-loop and while-loop, which are already present in the language.
  3. For-loop uses the iter() method for emulating the do-while loop in Python
  4. To convert a while-loop into a do-while loop in Python, we require just a True boolean as loop conditional.
  5. Both methods further require if-else conditions to break out of the infinite loop at the desired execution stage.

Further Reading

  1. Iter() method in Python
  2. While Loop in Python