Home » Python

do while loop in Python

Python do while loop: Here, we are going to learn how to implement a do while loop in python using while loop?
Submitted by IncludeHelp, on April 12, 2019

Python do while loop

Like other programming languages, do while loop is an exit controlled loop – which validates the test condition after executing the loop statements (loop body).

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

Python code to implement a do while loop using 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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.