Break and Continue Statements

'''
Break Statement:
The break-statement in Python is used to skip a loop prematurely i.e. before the loop has finished all its iterations.
We can use break inside a for or while loop while a certain condition is met and we want to stop the loop at that point.
'''

for i in range(12):
    if(i == 10):
        break
    print("5 x", i+1, "=", 5 * (i+1))
    
print("Loop ko chodkar nikal gaya")
#output : 5 x 1 = 5
#         5 x 2 = 10
#         5 x 3 = 15
#         5 x 4 = 20
#         5 x 5 = 25
#         5 x 6 = 30
#         5 x 7 = 35
#         5 x 8 = 40
#         5 x 9 = 45
#         5 x 10 = 50
#         Loop ko chodkar nikal gaya

'''
Continue Statement:
It skips the rest of the loop statements and causes the rest iteration to occur.
'''

for i in range(12):
    if (i == 10):
        print("Skip the iteration")
        continue
    print("5 x", i+1, "=", 5* (i+1))
#output:  5 x 1 = 5
#         5 x 2 = 10
#         5 x 3 = 15
#         5 x 4 = 20
#         5 x 5 = 25
#         5 x 6 = 30
#         5 x 7 = 35
#         5 x 8 = 40
#         5 x 9 = 45
#         Skip the iteration
#         5 x 11 = 55


'''
How to emulate do-while loop in Python?
The most common technique to emulate a do-while loop is to use an infinite loop with a break statement wrapped in an if statement that checks a given condition and breaks the iteration if the condition becomes true.
'''
i = 0
while True:
    print(i)
    i = i + 1
    if(i%10 == 0):
        break
#output = 0
#         1
#         2
#         3
#         4
#         5
#         6
#         7
#         8
#         9


    

Comments

Popular posts from this blog

Print Function

Arithmetic Operators

Sets in Python