Home » 
        Python
    
    
    Implement do while loop in Python
    
    
    
    
        
            By IncludeHelp Last updated : December 08, 2024
        
    
    Like other programming languages, do while loop is an exit controlled loop – which validates the test condition after executing the loop statements (loop body).
    Python do while loop
    In Python programming language, there is no such loop i.e. Python does not have a do while loop that can validate the test condition after executing the loop statement. But, we can implement a similar approach like a do while loop using while loop by checking using True instead of a test condition and test condition can be placed in the loop statement, and break the loop's execution using break statement – if the test condition is not true.
    Logic to Emulate a Do-while loop in Python
    Logic to implement an approach like a do while loop:
    
        - Use while loop with True as test condition (i.e. an infinite loop).
 
        - Write statements of loop body within the scope of while loop.
 
        - Place the condition to be validated (test condition) in the loop body
 
        - break the loop statement – if test condition is False.
 
    
    
    Examples to Implement do while Loop
    Example 1: Print the numbers from 1 to 10
# print numbers from 1 to 10
count = 1
while True:
    print(count)
    count += 1
    # test condition
    if count > 10:
        break
Output
1
2
3
4
5
6
7
8
9
10
    Example 2: Input a number and print its table and ask for user's choice to continue/exit
# python example of to print tables
count = 1
num = 0
choice = 0
while True:
    # input the number
    num = int(input("Enter a number: "))
    # break if num is 0
    if num == 0:
        break  # terminates inner loop
    # print the table
    count = 1
    while count <= 10:
        print(num * count)
        count += 1
    # input choice
    choice = int(input("press 1 to continue..."))
    if choice != 1:
        break  # terminates outer loop
print("bye bye!!!")
Output
Enter a number: 3
3  
6  
9  
12 
15 
18 
21 
24 
27 
30 
press 1 to continue...1
Enter a number: 19
19 
38 
57 
76 
95 
114
133
152
171
190
press 1 to continue...0
bye bye!!!  
Python Emulating Do-While Loop Exercise
Select the correct option to complete each statement about emulating a do-while loop in Python.
    - In Python, there is no native ___ loop, but we can emulate it using a while loop with a condition at the end.
        
    
 
    - To emulate a do-while loop, you can place the loop’s body inside a ___ block and then check the condition at the end of the loop.
        
    
 
    - In order to ensure the loop executes at least once, the condition should be checked ___ the loop's body.
        
    
 
	
	
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement