Does python have do while loops

Do while loop in Python

Python Certification Course: Master the essentials

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:

Читайте также:  Все виды гиперссылок html

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.

int 1, -2, 1.4, ‘v’, “a random string”, [1,3,4] (anything other than 0)
float 1, 0.1, 0.001, -3, (anything other than 0 or 0.0)
dict Anything other than <>
list Anything other than []
tuple Anything other than ()
str Anything 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.

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:

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.

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

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:

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

Источник

Python do…while Loop Statement Emulation

If you have come from other programming languages such as JavaScript, Java, or C#, you’re already familiar with the do. while loop statement.

Unlike the while loop, the do. while loop statement executes at least one iteration. It checks the condition at the end of each iteration and executes a code block until the condition is False .

The following shows the pseudocode for the do. while loop in Python:

do # code block while conditionCode language: PHP (php)

Unfortunately, Python doesn’t support the do. while loop. However, you can use the while loop and a break statement to emulate the do. while loop statement.

First, specify the condition as True in the while loop like this:

while True: # code blockCode language: PHP (php)

This allows the code block to execute for the first time. However, since the condition is always True , it creates an indefinite loop. This is not what we expected.

Second, place a condition to break out of the while loop:

while True: # code block # break out of the loop if condition breakCode language: PHP (php)

In this syntax, the code block always executes at least one for the first time and the condition is checked at the end of each iteration.

Python do…while loop emulation example

Suppose that you need to develop a number guessing game with the following logic:

  • First, generate a random number within a range e.g., 0 to 10.
  • Then, repeatedly prompt users for entering a number. If the entered number is lower or higher than the random number, give users a hint. If the entered number equals the random number, the loop stops.

The following program uses a while loop to develop the number guessing game:

from random import randint # determine the range MIN = 0 MAX = 10 # generate a secret number secret_number = randint(MIN, MAX) # initialize the attempt attempt = 0 # The first attempt input_number = int(input(f'Enter a number between and :')) attempt += 1 if input_number > secret_number: print('It should be smaller.') elif input_number < secret_number: print('It should be bigger.') else: print(f'Bingo! attempt(s)') # From the second attempt while input_number != secret_number: input_number = int(input(f'Enter a number between and :')) attempt += 1 if input_number > secret_number: print('It should be smaller.') elif input_number < secret_number: print('It should be bigger.') else: print(f'Bingo! attempt(s)') Code language: Python (python)

The following shows a sample run:

Enter a number between 0 and 10:5 It should be bigger. Enter a number between 0 and 10:7 It should be bigger. Enter a number between 0 and 10:8 Bingo! 3 attempt(s)Code language: Shell Session (shell)

Since the while loop checks for the condition at the beginning of each iteration, it’s necessary to repeat the code that prompts for user input and checking the number twice, one before the loop and one inside the loop.

To avoid this duplicate code, you can use a while loop to emulate do while loop as follows:

from random import randint # determine the range MIN = 0 MAX = 10 # generate a secret number secret_number = randint(MIN, MAX) # initialize the attempt attempt = 0 while True: attempt += 1 input_number = int(input(f'Enter a number between and :')) if input_number > secret_number: print('It should be smaller.') elif input_number < secret_number: print('It should be bigger.') else: print(f'Bingo! attempt(s)') break Code language: Python (python)
  • First, remove the code before the while loop.
  • Second, add the condition to stop the loop if the entered number equals the random number by using the break statement.

Summary

  • Python doesn’t support the do-while loop statement.
  • Use a while loop and the break statements to emulate a do. while loop in Python

Источник

Оцените статью