×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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 of implementation

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!!!  

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.