Jump Statements in Python
In this article, we will learn about the jump statements in Python using examples.
Jump statement has 3 types:
- Break
- Continue
- Pass
Break Statement in Python
In a loop, if break statement is used it exits from the loop. It not only exists from the current iteration but also from the loop. It goes on to other statements outside the loop.
Syntax:
while condition_1:
statement_1
statement_2
if condition_2:
break
You can check: Break and Continue Statement in Python
Example:
In the example below, we are calculating the sum of the given numbers in a list. Break statement is used to stop the execution after a certain iteration which in this case is 4.
list = [1,2,3,4,5] sum_1=0 count=0 for num in list: print(num) sum_1+=num count+=1 if(count == 4): break print("Sum=%d"%(sum_1))
Output:
1 2 3 4 Sum=10
Continue Statement in Python
If continue statement is used then it skips the remaining statements and goes back to the top of the loop.
Syntax:
for condition_1:
if condition_2:
continue
Example:
In this example, the continue statement is used to exit the current iteration if the count is equal to 7 therefore ‘count is: 7’ statement is omitted.
sum_1=0 count=0 while count < 8: sum_1 +=count count +=1 if(count == 7): continue print("Count is:%d"%(count)) print ("Sum is:%d"%(sum_1))
Output:
Count is:1 Count is:2 Count is:3 Count is:4 Count is:5 Count is:6 Count is:8 Sum is:28
Pass Statement
Pass statement is used when you create a function that does not have to be used yet. Nothing happens when we use this statement. It is a null operation.
Syntax:
for condition_1
pass
Example:
In this example, we have taken a word and used a pass statement everytime ‘s’ is encountered. Therefore in output the ‘s’ is omitted.
for i in 'Mississippi': if(i == 's'): pass else: print(i)
Output:
M i i i p p i
Leave a Reply