Rolex Pearlmaster Replica
  Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
This article is part of in the series
Published: Tuesday 18th March 2025

tutorial on python do while loop

 

In any programming language, including Python, loops are essential for many purposes like iterating over sequences, running repetitive tasks, and handling dynamic data structures. If you have been using PythonCentral for learning Python, you would have realized that Python gives you "for" and "while" loops but not a built-in "do-while loop". While the do-while loop comes in-built in other programming languages like C, JavaScript, and Java, Python is an exception.

At PythonCentral, we will teach you how to simulate a do-while loop using a simple "while" loop but with a specific structure. Get. Set. Learn!

What is a "Do-While" Loop?

A "do-while" loop runs the loop body at least once before checking the condition. Let us take an example syntax to understand better. A typical do-while loop in C language looks like this:

int x = 0;
do {
printf("Iteration: %d", x);
x++;
} while (x < 5);

While we learnt that Python does not have a direct approach for do-while, it still lets us simulate one using a while loop.

How to Simulate a Do While Loop in Python

To simulate a do-while loop in Python, let us use a "while" loop with a break condition inside the loop body. Here is how you can write a Python code for the same example written in C language earlier:

x = 0
while True:
print(f"Iteration: {x}")
x += 1
if x >= 5:
break

Let us break down this code for you to understand better. The loop executes at least once, because the condition is "True" initially. Inside the loop, we performed the required operation. We then checked the exit condition i.e., x>=5, and break out when met.

Use Cases of Do While Loops in Python

How to Validate Input with Python Do While

One of the most common use cases for a do-while loop is validating user input. Here is one sample to validate input:

while True:
number = input("Enter a number between 1 and 10: ")
if number.isdigit() and 1 <= int(number) <= 10:
break
print("Invalid input. Try again.")

Build Menu Driven Programs

Here is an example syntax to build menu-driven programs.

while True:
print("1. Start")
print("2. Settings")
print("3. Exit")
choice = input("Enter your choice: ")

if choice == "3":
print("Exiting...")
break

API Polling with Python

If you want to check the status of API, here is how you can do it with a do-while loop:

import time
import random

while True:
status = random.choice(["processing", "completed"])
print(f"Checking API status: {status}")
if status == "completed":
break
time.sleep(2) # Simulate delay

Do While Loop Best Practices

Now that we have understood the basics and some example syntaxes, let us learn how to write meaningful or beautiful code.

  • Always include a break condition to avoid infinite loops.
  • Use meaningful conditions to ensure readability.
  • Ensure the loop body executes at least once before checking conditions.
  • Consider alternative approaches like recursion for certain cases.

Wrapping Up

Python does not have a native do-while loop? Not a problem. We now know how to simulate a do-while loop in Python by using a while loop with a break condition. Use this loop for menu-driven programs, API polling mechanisms, input validation, and many more use cases. By understanding Python loop constructs, you can write efficient, flexible, and error-free code for a lot of applications. Let us know what you built with Python do while loop in comments.

Related Articles

Latest Articles


Tags

  • Parsing
  • tail
  • merge sort
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • unittest
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • Studio
  • excel
  • sgd
  • deeplearning
  • pandas
  • class python
  • intersection
  • logic
  • pydub
  • git
  • Scrapping
  • priority queue
  • quick sort
  • web development
  • uninstall python
  • python string
  • code interface
  • PyUnit
  • round numbers
  • train_test_split()
  • Flask module
  • Software
  • FL
  • llm
  • data science
  • testing
  • pathlib
  • oop
  • gui
  • visualization
  • audio edit
  • requests
  • stack
  • min heap
  • Linked List
  • machine learning
  • scripts
  • compare string
  • time delay
  • PythonZip
  • pandas dataframes
  • arange() method
  • SQLAlchemy
  • Activator
  • Music
  • AI
  • ML
  • import
  • file
  • jinja
  • pysimplegui
  • notebook
  • decouple
  • queue
  • heapify
  • Singly Linked List
  • intro
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Download
  • No
  • nlp
  • machiine learning
  • dask
  • file management
  • jinja2
  • ui
  • tdqm
  • configuration
  • deque
  • heap
  • Data Structure
  • howto
  • dict
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • KMS
  • Office
  • modules
  • web scraping
  • scalable
  • pipx
  • templates
  • python not
  • pytesseract
  • env
  • push
  • search
  • Node
  • python tutorial
  • dictionary
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • linspace
  • numbers_list
  • Tool
  • Key
  • automation
  • website data
  • autoscale
  • packages
  • snusbase
  • boolean
  • ocr
  • pyside6
  • pop
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Assertions
  • Matplotlib Plotting
  • any() Function
  • Activation
  • Patch
  • threading
  • scrapy
  • game analysis
  • dependencies
  • security
  • not operation
  • pdf
  • build gui
  • dequeue
  • linear search
  • Add Node
  • Python tools
  • function
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • matplotlib
  • Recursion Limit
  • License
  • Pirated
  • square root
  • website extract python
  • steamspy
  • processing
  • cybersecurity
  • variable
  • image processing
  • incrementing
  • Data structures
  • algorithm
  • Print Node
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • Pygame
  • NumPy Pad()
  • Unlock
  • Bypass
  • pytorch
  • zipp
  • steam
  • multiprocessing
  • type hinting
  • global
  • argh
  • c vs python
  • Python
  • stacks
  • Sort
  • algorithms
  • install python
  • Scopes
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • % Operator
  • Python YAML
  • Crack
  • Reddit
  • lightning
  • zip files
  • python reduce
  • library
  • dynamic
  • local
  • command line
  • define function
  • Pickle
  • enqueue
  • ascending
  • remove a node
  • Django
  • function scope
  • Tuple in Python
  • pandas groupby
  • pyenv
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • Hack
  • sdk
  • python automation
  • main
  • reduce
  • typing
  • ord
  • print
  • network
  • matplotlib inline
  • Pickling
  • datastructure
  • bubble sort
  • find a node
  • Flask
  • calling function
  • tuple
  • GroupBy method
  • Pythonbrew
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Keygen
  • cloud
  • pyautogui
  • python main
  • reduce function
  • type hints
  • python ord
  • format
  • python socket
  • jupyter
  • Unpickling
  • array
  • sorting
  • reversal
  • Python salaries
  • list sort
  • Pip
  • .groupby()
  • pyenv global
  • NumPy arrays
  • Modulo
  • OpenCV
  • Torrent
  • data
  • int function
  • file conversion
  • calculus
  • python typing
  • encryption
  • strings
  • big o calculator
  • gamin
  • HTML
  • list
  • insertion sort
  • in place reversal
  • learn python
  • String
  • python packages
  • FastAPI
  • argparse
  • zeros() function
  • AWS Lambda
  • Scikit Learn
  • Free
  • classes
  • turtle
  • convert file
  • abs()
  • python do while
  • set operations
  • data visualization
  • efficient coding
  • data analysis
  • HTML Parser
  • circular queue
  • effiiciency
  • Learning
  • windows
  • reverse
  • Python IDE
  • python maps
  • dataframes
  • Num Py Zeros
  • Python Lists
  • Fprintf
  • Version
  • immutable
  • python turtle
  • pandoc
  • semantic kernel
  • do while
  • set
  • tabulate
  • optimize code
  • object oriented
  • HTML Extraction
  • head
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • Pytest
  • pandas.reset_index
  • NumPy
  • Infinite Numbers in Python
  • Python Readlines()
  • Trial
  • youtube
  • interactive
  • deep
  • kernel
  • while loop
  • union
  • tutorials
  • audio
  • github
  • Python is a beautiful language.