Break is the keyword in Python, used to bring the program control out of the loop. In other word we can say that the break statement is used to leave the current execution of the program and control moves to the next line out of the loop. In case of nested loop, it breaks inner loop first then proceeds to outer loops.
The break is commonly used in the cases where we need to break the loop for a given condition. The syntax of the break statement in Python is:
#loop statements break; |
---|
Let's see some examples of break statement.
Example1-break statement with for loop
for i in range(5): if i==3: break print(i) |
---|
Output
0 1 2 |
---|
In above example, a list is iterating by for loop, when i matches with value 3, the break statement executed and the loop terminates..
Example 2-breaking out a loop for string
for my_str in "Python":
if my_str=='o':
break
print(my_str)
Output
P y t h |
---|
When the character is found in the list, break starts executing and iteration stops immediately and the next line of print statement is printed.
Example 3-break statement with while loop
#break statement example
i = 0;
while 2:
print(i)
i = i+2;
if i == 22:
break
In above program, unless the value of i is below 22, the loop is continuing and showing the numbers start from 0(i=0) and increased each time by 2 (i=i+2) , but when the value of i is equal to 22, it terminates by break statement.
Example 4-break statement with nested loop
#break statement example
n = 2
while True:
i = 1
while i<=10:
print("%d X %d = %d\n" %(n, i, n*i))
i+=1
choice=int(input("Do you want to continue printing the table? Press 0 for no:"))
if choice==0:
print("existing the program...")
break
n+=1
There are two loops available here, inner loop and outer loop. Inner loop is responsible for printing the multiplication table, where as the outer loop is responsible for incrementing the value of n. When the inner loop completes the execution the control is transferred to the outer loop. when 0 is entered by the user the number is increased by 1 and next multiplication table starts.