In Python, the break statement is used to terminate the execution of the nearest enclosing loop in which it appears.
When the break statement is encountered inside a loop, the loop is immediately exited, and the program continues with the statement immediately following the loop. When the loops are nested, the break is only exited from the loop containing it.
The syntax of the break statement is given below:
break
Example 1:
n=int(input("Enter the value of n=")) sum=0 for i in range(1,n+1): if(i%2==0): sum=sum+i if(i%2!=0): break print("The sum is=",sum)
Output:
Enter the value of n=100
The sum is= 0
Example 2:
i=1 while(i<=20): print(i,end=" ") if(i==5): break i=i+1
Output:
1 2 3 4 5
Example 3:
n=int(input("Enter the value of n=")) for i in range(1,n+1): print() for j in range(1,i+1): print("*",end=" ") if(i==5): break
Output:
Enter the value of n=10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Example 4:
n=int(input("Enter the value of n=")) for i in range(1,n+1): print() for j in range(1,i+1): print(j,end=" ") if(i==5): break
Output:
Enter the value of n=5
1 1 2 1 2 3 1 2 3 4 1
Leave a comment