Python Menu

Break & Continue statements in Python


break statement :

The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.

In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.


Syntax:
break

 Python Example Program - Break statement in python


Example:
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1
Output:
1
2
3

 Python Example Program -to print sum of first 6 numbers using break statement


Example:
nsum = 0
count = 0
for count in range(10):
    nsum = nsum + count
    if count== 6:
        break
print("Sum of first 6 Numbers is: ", nsum)
Output:
Sum of first  6 Numbers is:  21

continue statement :

The continue statement skips the remaining lines of code inside the loop and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular condition.In other words, The continue statement in python is used to bring the program control to the beginning of the loop.


Syntax:
continue

 Python Example Program - Continue statement in python


Example:
str1 = input("Enter any String : ") 
for i in str1:  
    if i == 'h':  
        continue;
    print(i,end=" ");
Output:
Enter any String: python
p y t o n

 Python Example Program - to print odd numbers using continue statement


Example:
num = 0
print("Odd numbers in between 1 to 10")
while(num < 10):
    num = num + 1
    if (num % 2) == 0:
        continue
    print(num)
Output:
Odd numbers in between 1 to 10
1
3
5
7
9

Next Topic :Strings Sequence in Python