Break Statement Examples

 #Example 1
print("---------->>>>example 1")
print("                       ")
list =[1,2,3,4]
print("given list is: ",list)
print("                       ")
count = 1;  
for i in list:  
    if i == 4:  
        print("item matched")  
        count = count + 1;  
        break  
print("found at",count,"location")
print("=============================================")

#Example 2
print("---------->>>>example 2")
print("                       ")

str = "python"
print("given string is: ",str)
print("                       ")

for i in str:  
    if i == 'o':  
        break  
    print(i);


print("=============================================")

#Example 3
print("---------->>>>example 3: break statement with while loop")
print("                       ")
i = 0;  
while 1:  
    print(i," ",end=""),  
    i=i+1;  
    if i == 10:  
        break;  
print("came out of while loop");


print("=============================================")

#Example 4
print("---------->>>>example 4:")
print("                       ")

n=2  
while 1:  
    i=1;  
    while i<=10:  
        print("%d X %d = %d\n"%(n,i,n*i));  
        i = i+1;  
    choice = int(input("Do you want to continue printing the table, press 0 for no?"))  
    if choice == 0:  
        break;      
    n=n+1  


Output:

---------->>>>example 1
                       
given list is:  [1, 2, 3, 4]
                       
item matched
found at 2 location
=============================================
---------->>>>example 2
                       
given string is:  python
                       
p
y
t
h
=============================================
---------->>>>example 3: break statement with while loop
                       
0  1  2  3  4  5  6  7  8  9  came out of while loop
=============================================
---------->>>>example 4:
                       
2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for no?0