Python do while loop example

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:

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

Читайте также:  Java software development projects

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.

Читайте также:  Gis programming in python

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 Example

Dionysia Lemonaki

Dionysia Lemonaki

Python Do While – Loop Example

Loops are a useful and frequently used feature in all modern programming languages.

If you want to automate a specific repetitive task or prevent yourself from writing repetitive code in your programs, using a loop is the best option for that.

Loops are a set of instructions that run repeatedly until a condition is met. Let’s learn more about how loops work in Python.

Loops in Python

There are two types of loops built into Python:

Let’s focus on how you can create a while loop in Python and how it works.

What is a while loop in Python?

The general syntax of a while loop in Python looks like this:

while condition: execute this code in the loop's body 

A while loop will run a piece of code while a condition is True. It will keep executing the desired set of code statements until that condition is no longer True.

A while loop will always first check the condition before running.

If the condition evaluates to True then the loop will run the code within the loop’s body.

For example, this loop runs as long as number is less than 10 :

number = 0 while number < 10: print(f"Number is !") number = number + 1 
Number is 0! Number is 1! Number is 2! Number is 3! Number is 4! Number is 5! Number is 6! Number is 7! Number is 8! Number is 9! 

Here, the variable number is set to 0 initially.

number is then incremented by 1 . The condition is re-evaluated and it is again True, so the whole procedure repeats until number is equal to 9 .

This time Number is 9! is printed and number is incremented, but now number is equal to 10 so the condition is no longer met and therefore the loop is terminated.

It's possible that the while loop never runs if it doesn't meet the condition, like in this example:

Since the condition is always False, the instructions in the loop's body don't execute.

Don't create infinite loops

As you saw from the example above, while loops are typically accompanied by a variable whose value changes throughout the duration of the loop. And it ultimately determines when the loop will end.

If you do not add this line, you will create an infinite loop.

number will not be incremented and updated. It will always be set and remain at 0 and therefore the condition number < 10 will be True forever. This means that the loop will continue to loop forever.

 # don't run this number = 0 while number < 10: print(f"Number is !") 
Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! . 

It is the same as doing this:

 #don't run this while True: print("I am always true") 

What if you find yourself in a situation like this?

Читайте также:  Online code editor javascript

Press Control C to escape and end the loop.

What is a do while loop?

The general syntax of a do while loop in other programming languages looks something like this:

For example, a do while loop in C looks like this:

#include int main(void) < int i = 10; do < printf("the value of i: %i\n", i); i++; >while( i

What is unique in do while loops is the fact that the code in the loop block will be executed at least one time.

The code in the statement runs one time and then the condition is checked only after the code is executed.

So the code runs once first and then the condition is checked.

If the condition checked evaluates to true, the loop continues.

There are cases where you would want your code to run at least one time, and that is where do while loops come in handy.

For example, when you're writing a program that takes in input from users you may ask for only a positive number. The code will run at least once. If the number the user submits is negative, the loop will keep on running. If it is positive, it will stop.

Python does not have built-in functionality to explicitly create a do while loop like other languages. But it is possible to emulate a do while loop in Python.

How to emulate a do while loop in Python

To create a do while loop in Python, you need to modify the while loop a bit in order to get similar behavior to a do while loop in other languages.

As a refresher so far, a do while loop will run at least once. If the condition is met, then it will run again.

The while loop, on the other hand, doesn't run at least once and may in fact never run. It runs when and only when the condition is met.

So, let's say we have an example where we want a line of code to run at least once.

secret_word = "python" counter = 0 while True: word = input("Enter the secret word: ").lower() counter = counter + 1 if word == secret_word: break if word != secret_word and counter > 7: break 

The code will run at least one time, asking for user input.

It is always guaranteed to run at least once, with True , which otherwise creates an infinite loop.

If the user inputs the correct secret word, the loop is terminated.

If the user enters the wrong secret word more than 7 times, then the loop will be completely exited.

The break statement allows you to control the flow of a while loop and not end up with an infinite loop.

break will immediately terminate the current loop all together and break out of it.

So this is how you create the a similar effect to a do while loop in Python.

The loop always executes at least once. It will continue to loop if a condition is not met and then terminate when a condition is met.

Conclusion

You now know how to create a do while loop in Python.

If you're interested in learning more about Python, you can watch the 12 Python Projects video on freeCodeCamp's YouTube channel. You'll get to build 12 projects and it's geared towards beginners.

freeCodeCamp also has a free Python Certification to help you gain a good understanding and a well rounded overview of the important fundamentals of the language.

You'll also get to build five projects at the end of the course to practice what you've learned.

Thanks for reading and happy learning!

Источник

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