do-while python examples

A Do-While loop checks a condition after initially executing the statement. At any given point, a do-while loop is executed at least once. This is what is referred to as a post-test loop. Since Python does not explicitly handle do-while, we will demonstrate with examples of how to emulate the process.

There’s actually a new keyword for this do-while for other programming languages. However, in Python, we’re just going to use a normal loop and modify it to get the same behaviour.

Do-while loop

A do-while loop executes one time whether or not the condition is true or false. For instance, if you’re printing numbers, it’ll always print that first number, and this might seem a little bit weird.

You’re going to want to do something one time, and then if a certain condition is met, do it again. You know, for example, you’re trying to log into a website; you put in your username and password one time, and if it’s not correct, you do it again.

So that’s a simple scenario but let’s just go through a normal standard while loop and show you how this works.

Let’s first look at a normal while loop before we can explore how to make a do-while loop.

j =0
while j < 10:
  print(j)
  j +=1

The above code will print the values from 1 to 9. If we instead initialize j to 100 as follows:

j =100
while j < 10:
  print(j)
  j +=1

We get nothing printed when we run the code. However, in a do-while, 100 should be printed at least once and then no more because it doesn’t meet the condition.

We are going to look at two ways to do this.

The first way involves you taking the body, and you pretty much put it on the outside as well and make sure the spacing and everything is right, so it’s going to look like the code block below.

J =100
print(j)
while j < 10:
  print(j)
  j +=1

And now the 100 shows up at least once, and the condition is no longer met, and it therefore stops. You could also increment j here if you want. So you could say, j plus equals one, and then it would increment it to 101 if you need to do the increment for every single iteration as follows.

J =100
print(j)
j +=1
while j < 10:
  print(j)
  j +=1

But in this situation, it doesn’t really matter. So, this is one way to do it, and that’s pretty much the simplest structure. However, if you have a considerable body for the while loop, you might not want to duplicate all of that code. In this case, our example is a straightforward one because we have a print statement. So, it’s not a huge deal.

The next example illustrates another structure where you don’t have to repeat the whole code before and within the while loop.

j =100
while True:
  print(i)
  j += 1
  if j < 99:
    break

In the example above, while true, we’re just going to create a loop that goes on forever. Within this loop, we’re going to print j and then increment j by one, and then we’re going to check for a condition to break.

In our case, if j is greater than 99, then we’re going to break out of the loop, and we get 100.

Let’s go through this step by step.

We set j to 100

We print j, which comes out as 100.

We increment it, which goes to 101, and then we check if it’s greater than 99, which it is, and it breaks this loop. It can be used in a similar way to the original loop. Let’s say j to 0, and we run this, and we still get 0
through 9.

Everything works exactly the same. However, now we know it will execute at least one time.

Conceptual Representation of a Do-While Loop

do-while loop
do-while loop

do {
// block of statements

} while(condition)

Example of a Do While Loop in Python

j = 1

while True:
	print(j)
	j = j + 1
	
	if(j > 5) :
		break

Using the above example, there two cases when the loop terminates. The first one is when the condition within the loop becomes false. The second one is when the code hits the break statement within the loop body.

Example to print the first ten integers using Do-While:

i = 1 
while True: 
	print(i) 
	i = i + 1 
	if(i > 10): 
		break

Here, the value of i is printed way before checking the condition, which is similar to how a do-while loop works in Java and C++. However, the only difference is that it is just an emulation in Python. And we can achieve this through the use of functions.

Do-While Loop by wrapping the commands in a Function:

k = 20

def do_while_commands():
        k = k+2
        print(k)


do_while_commands()
while(k <=15):
        do_while_commands()

This example demonstrates that do_while_commands() functions run at least once before the while loop is invoked.
The function is not run when the while loop is called because the initial value of k is way more than the minimum value specified in the condition.

Break

j = 1

while True:
	print(j)
	j = j + 1
	
	if(j> 5) :
		break

The above example is essential in illustrating how to break out of the do-while loop. When j exceeds 5, the execution will be stopped.

Continue

The continue statement returns control to the beginning of the loop. It rejects all the statements left in the current iteration and controls the top of the loop. Besides being used in a do-while, it is also applicable to for and while loops.

i = 1 
while True: 
	if (i ==8):
	 	continue
	print(i) 
	i = i + 1 
	if(i > 10): 
		break

Do-While Example

import random

while True:
 	val =random.randint(1, 500)
	print(val)
	if (val > 450):
		break

In this example, we first import the random library to generate random numbers.
We have instructed the computer to generate random numbers from one to five hundred in the while loop body. The number generated will then be printed, which goes on and on because of the true condition.

However, we have a condition check to stop when the number generated exceeds four hundred and fifty. Note that the first number is guaranteed to be printed in this code.

Variation of the Do-While Example above

import random
num =0
while num < 450:
	num = random.randint(1,500)
	print(num)

Here, we first initialize the value of num to zero. Then we place the check condition in the while loop for values below four hundred and fifty.

Then in the while loop, we generate a random number between one and 500 and assign it to the variable num. Finally, we can then print the num value.

The difference between this example and the previous is this does not use a break condition.

Summary

Control statements are essential structures in any worthwhile software development. Grasping the details of using the various control statements or what we call loops is pertinent to succeeding in programming.

Whereas continue and break are essential in controlling your program flow, be wary of accidentally creating infinite loops.

In this article, we examined the do-while loop. Python supports while loop but not do-while. However, if you still intend to use it, you can do so by emulating it.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *