The Wayback Machine - https://web.archive.org/web/20241117043543/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.



Previous Article
Next Article

Similar Reads

Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Specifying the increment in for-loops in Python
Let us see how to control the increment in for-loops in Python. We can do this by using the range() function. range() function range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well
2 min read
How to make a box with the help of nested loops using Python arcade?
Arcade library is modern framework currently used in making 2D games. Nested loop discussed here are analogous to nested loops in any other programming language. The following tutorial will step by step explain how to draw a box with the help of nested loops using Python's arcade module. Import arcade library.Here we will be using circles to form a
2 min read
Use for Loop That Loops Over a Sequence in Python
In this article, we are going to discuss how for loop is used to iterate over a sequence in Python. Python programming is very simple as it provides various methods and keywords that help programmers to implement the logic of code in fewer lines. Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, s
3 min read
Python Nested Loops
In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc. Python Nested Loops Syntax:Outer_loop Expression:     Inner_loop Expression:
9 min read
Python For Loops
The For Loops in Python are a special type of loop statement that is used for sequential traversal. Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary. In Python, there is no C style for loop, i.e., for (i=0; I <n; i++). The For Loops in Python is similar to each loop in other languages, used fo
8 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
How to use while True in Python
In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Example: While Loop with True C/C++ Code # Python program to demonstrate # while loop with True while True: pass If we run
2 min read
Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python.
3 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples. Wha
6 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
9 min read
How to fix "error 403 while installing package with Python PIP"?
When working with Python, pip is the go-to tool for managing packages. However, encountering a "403 Forbidden" error can be frustrating. This error typically indicates that the server refuses to fulfill the request, often due to permissions or access restrictions. In this article, we'll delve into the causes of this error and explore various soluti
4 min read
How to Disable Logging While Running Unit Tests in Python Django
It is never necessary to log everything while testing because it may flood the terminal with unnecessary log messages. These logs are useful during development but can be distracting when focusing on the actual test results. Disabling logging during unit tests can make our output cleaner and easier to understand. There are different ways to disable
4 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to preserve Function Metadata while using Decorators?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.Note: For more information, refer Decorators in Python How to preserve Metadata? This
2 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
7 Mistakes You Should Avoid While Building a Django Application
Django...We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications. A lot of common features
6 min read
How to not get caught while web scraping ?
In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
5 min read
Protecting sensitive information while deploying Django project
There will be a lot of sensitive information in our Django project resided in the settings.py, or local variables containing sensitive information or the POST request made using forms. So while deploying a Django project we always have to make sure they are protected especially the repositories that are publicly available. When a project is deploye
3 min read
Pyspark dataframe: Summing column while grouping over another
In this article, we will discuss how to sum a column while grouping another in Pyspark dataframe using Python. Let's create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSe
4 min read
How to Remove Index Column While Saving CSV in Pandas
In this article, we'll discuss how to avoid pandas creating an index in a saved CSV file. Pandas is a library in Python where one can work with data. While working with Pandas, you may need to save a DataFrame to a CSV file. The Pandas library includes an index column in the output CSV file by default. Further in the article, we'll understand the d
3 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
Avoid these mistakes while preparing for the CAT Exam
The CAT exam is arguably the most important exam in India for students wanting to secure the coveted MBA seats in various management institutes of the country. This is obvious from the high level of competition with more than two lakh candidates competing for seats in various MBA programs such as Finance, Marketing, Operations, etc. and only 11 can
6 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg