Introduction
In this article, we will discuss break and continue statements. Break and continue statements also known as jumping statements. Sometimes we need to skip some iterations or maybe we need to stop our iteration, then we use a break and continue statements.
Break statement
It allows us to exit the loop at any point in condition. When a break statement encountered inside the loop then our loop terminates and our control jump out from the loop. For example, there is a list of numbers and you want to search a particular number inside the list, then you will start from the beginning and check each and every number with your search element, and if the search number found inside the list then you will never check further and break the loop.
Syntax:
Example 1:
- Names=["Sourabh Somani","DJ","Dinesh Beniwal","Abhishek Jaiswal"]
- Key=input("Please Enter the name which you want to search : ")
- i=1;
- for name in Names:
- if(Key==name):
- print(name," is found at ",i," Position in the List")
- break
- i+=1;
- else:
- print("Name is not present in the list")
Output:
Example 2
-
-
-
- num = int(input("Enter a Number : "))
- for i in range(2,num):
- if(num%i==0):
- print("%d is not a prime number..."%num)
- break
- else:
- print("%d is a prime number..."%num)
Example 3:
- while(True):
- a=int(input("Please Enter 1st number :"))
- b=int(input("Please Enter 2nd number :"))
- print()
- print("MENU")
- print("_____________________")
- print("PRESS 1 FOR ADD")
- print("PRESS 2 FOR SUBTRACT")
- print("PRESS 3 FOR MULTIPLICATE")
- print("PRESS 4 FOR DIVIDE")
- print("PRESS 5 FOR EXIT")
- print("_____________________")
- print()
- choice=int(input("Enter your choice : "))
- if(choice==1):
- print("Sum of %d and %d is %d"%(a,b,a+b))
- elif(choice==2):
- print("Subtraction of %d and %d is %d"%(a,b,a-b))
- elif(choice==3):
- print("multiplication of %d and %d is %d"%(a,b,a*b))
- elif(choice==4):
- print("Division of %d and %d is %d"%(a,b,a/b))
- elif(choice==5):
- print("Bye Bye")
- break;
- else:
- print("Invalid Choice");
- print()
Output:
Continue
Continue is used when you want to skip certain iterations of the loop. This means it suspend the execution of the loop for that iteration and transfer control back to the loop for the next iteration. For example, suppose you want to print numbers from 1-30, but you don't want to print multiples of the 5, then you will execute your loop from 1 to 30, but you will skip the loop where the number will be divided by 5.
Syntax:
- for i in range(1,31):
- if(i%5==0):
- continue
- print(i)
Output:
Example 2:
-
-
-
-
- name=input("Please Enter a String : ")
- new_str=""
- for ch in name:
- if(ch=='A' or ch=='E' or ch=='I' or ch=='O'or ch=='U' or ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u'):
- continue
- new_str+=ch
- print(new_str)
Output: