Do While Loop in Python

Do While Loop in Python programming will execute the code block once, before checking if the condition is true, and repeat a specific block of code until the condition is met.

General form of While Loop


while this condition is true:
	do this
	and this
	and this
	and this
if check condition if true:
	break

Program Printing 0 to 10 using Do While Loop

Program

a = 0
while True: #executing the statement.
    print(a)
    a = a + 1 #adding 1 to 'a' value.
    if a == 11: #if 'a' value Equal to 11 then
        break #Break the statement.
Output
0
1
2
3
4
5
6
7
8
9
10

Password Program using Do While Loop

Program

while True: #executing the statement.
    val = input("Please Enter Password: ")
    if val == "HiLaLs": #if 'val' value Equal to "HiLaLs" then
        print("Password Correct!")
        break #Break the statement.
Output
Please Enter Password: bilal
Please Enter Password: 12345
Please Enter Password: HiLaLs
Password Correct!

Program Do While Loop Password Another Program
Program

while True: #executing the statement.
    val = input("Please Enter Password: ")
    if val == "HiLaLs": #if 'val' value Equal to "HiLaLs" then
        print("Password Correct!")
        break #Break the statement.
    else: #if not then
        print("Password Invalid!") #print this.
Output
Please Enter Password: bilal
Password Invalid!
Please Enter Password: 12345
Password Invalid!
Please Enter Password: admin
Password Invalid!
Please Enter Password: HiLaLs
Password Correct!

Program Printing Triangle using Do While Loop
Program

a = 1
while True: #loop looping.
    b = 0
    while True: #loop looping.
        print(" *", end="")
        b += 1 #addning 1 to 'b' value.
        if b == a: #if 'b' value equal to 'a' value then
            print()
            break #Break statement.
    a += 1 #adding 1 to 'a' value.
    if a == 10: #if 'a' value equal to 10 then
        break #Break statement.
Output
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *