The Wayback Machine - https://web.archive.org/web/20250202232023/https://www.geeksforgeeks.org/python-do-while/
Open In App

Python Do While Loops

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java.

In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is initially True and then break out of the loop when the desired condition is met.

Do while loop

Do while loop is a type of control looping statement that can run any statement until the condition statement becomes false specified in the loop. In do while loop the statement runs at least once no matter whether the condition is false or true.

Syntax of do while loop:

do{
// statement or
// set of statements
}
while(condition)

Example of do while loop in C++

In this example, we are going to print multiple of 2 using the do while loop. So, that we can understand the working of do while loop.

C++
#include <iostream>
using namespace std;

int main() {

    int i=0;
      // Defining do while loop 
      // to write multiple of 2
      do{
      i++;
      cout<<"2 x "<<i<<"="<<2*i<<endl;
    }while(i<5);
  
    return 0;
}

Output: In the below output we can clearly see that program also prints “2 x 5=10” even though 5 is not less than 5.

2 x 1=2
2 x 2=4
2 x 3=6
2 x 4=8
2 x 5=10

Examples of do while loop in Python : 

Example 1 :

In this example, we are going to implement the do-while loop in Python using the while loop and if statement in Python and comparing the while loop with the do-while loop in python.

Python
# defining list of strings
list1 = ["geeksforgeeks", "C++",
         "Java", "Python", "C", "MachineLearning"]

# initialises a variable
i = 0

print("Printing list items\
 using while loop")
size = len(list1)
# Implement while loop to print list items
while(i < size):
    print(list1[i])
    i = i+1

i = 0

print("Printing list items\
 using do while loop")

# Implement do while loop to print list items
while(True):
    print(list1[i])
    i = i+1
    if(i < size and len(list1[i]) < 10):
        continue
    else:
        break

Output: The while is printing the items in the list. The Do while loop is having two conditions for terminating.

The pointer of the list reached its last+1 position and any element of the list index having length >=10. In this code output, we can see that-

The Do While loop is terminated, because the condition len(list1[5])<10 is not fulfilling.

Printing list items using while loop
geeksforgeeks
C++
Java
Python
C
MachineLearning
Printing list items using do while loop
geeksforgeeks
C++
Java
Python
C

Example 2:

Python
total = 0
# loop will run at least once
while True:
    # ask the user to enter a number
    num = int(input("Enter a number (or 0 to exit): "))

    # exit the loop if the user enters 0
    if num == 0:
        break
    total += num

# print the total
print("Total:", total)

Output: In this code, we can see that a while loop is running and accepting the input from the user and adding it. When 0 is entered then it will break out of the loop and print the sum of all numbers which adds input by the user before 0.

Enter a number (or 0 to exit): 1
Enter a number (or 0 to exit): 3
Enter a number (or 0 to exit): 2
Enter a number (or 0 to exit): 0
Total: 6

Python Do While Loops – FAQs

Is There a Do-While Loop in Python?

Python does not have a built-in do-while loop construct that is found in many other programming languages like C, C++, or Java. Instead, Python provides the standard while loop and for loop for handling iterative operations. However, similar behavior to a do-while loop can be simulated using other loop constructs in Python.

What is the Use of Do-While Loop?

The do-while loop is used when you want to execute a block of code at least once before evaluating a condition. Unlike a standard while loop that checks the condition at the beginning, the do-while loop checks the condition after the code inside the loop has executed. This guarantees that the loop body will run at least once, which is useful when the condition to terminate the loop depends on some processing done within the loop body.

How Can You Simulate a Do-While Loop in Python?

Since Python doesn’t support the do-while loop directly, you can simulate it using a while loop with a condition that initially guarantees entry into the loop, often True, and a break condition at the end based on your actual stopping criteria:

while True:
# Loop body: Code you want to execute at least once
print("This runs at least once")

# Condition to check to continue/stop
if not continue_condition:
break

What is the Difference Between For, While, and Do-While Loop in Python?

  • For Loop: Typically used for iterating over a sequence (like a list, tuple, dictionary, or string) or any iterable object. The loop iterates for each element in the sequence until the sequence is exhausted.
  • While Loop: Runs as long as a specified condition is True. It’s used when the number of iterations is not known before the loop starts and depends on dynamic conditions during execution.
  • Do-While Loop: As discussed, this would execute its body at least once before checking a condition at the end of the loop. Python does not support this natively but can be mimicked using the method shown above.

Why Doesn’t Python Have Do While?

Python aims for simplicity and readability in its syntax. The inclusion of a do-while loop is often redundant because its functionality can be achieved with a while loop by arranging conditions and controls appropriately. This design choice keeps the language straightforward and minimizes the learning curve and potential for errors.

Which Loop is Faster in Python?

The performance of for and while loops in Python is generally similar for comparable tasks. The speed can depend more significantly on what you’re doing inside the loop rather than the type of loop itself. However, for loops may have a slight edge in cases where the iteration count is known beforehand or when iterating directly over an iterable, as Python’s for loops are highly optimized for these scenarios.

When considering performance, it is more important to focus on what happens inside the loop, the efficiency of the algorithms you use, and how you manage memory and data structures than on the choice between for and while.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg