PREV NEXT
Python Jump Statements are divided into 3 types. They are,
- break
- continue
- pass
1. Break statement:
break statement is used to exit from the iterative statements (loops) such as for, while. Use case of this statement terminates the execution of loop immediately, and then program execution will jump to the next statements.
Syntax 1:
while condition1:
statement1
statement2
if condition2:
break
Syntax2:
for var in sequence:
statement1
statement2
if condition:
break
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
list = [1,2,3,4,5,6] s=0 c=0 for num in list: print num s+=num c+=1 if(c == 3): break print "sum is =%d"%(s) |
Output:
1
2 3 sum is =6 |
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
s=0 c=0 while c < 6: s+=c c+=1 if(c == 3): break print "sum is :%d"%(s) |
Output:
sum is =3
|
Continue statement:
continue statement is used to continue the loop execution i.e. to get back to the top of the iterative statements (loops) such as for, while. Use case of this statement stops the further statement execution of loop immediately.
Example 1:
Below is the example for use case of continue statement. If we observe the below code, it will skip the print “count is:5” when the count reaches to 5 and take the control to the top of the while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
s=0 c=0 while c < 6: s+=c c+=1 if(c == 5): continue print "count is:%d"%(c) print "sum is:%d"%(s) |
Output:
count is:1
count is:2
count is:3
count is:4
count is:6
sum is :15
|
Example 2:
Below is the example for use case of continue statement. If we observe the below code, it will skip the print “count is:5” when the count reaches to 5 and take the control to the top of for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
s=0 for c in range(1,9): s+=c c+=1 if(c == 5): continue print "c is:%d"%(c) print "sum is =%d"%(s) |
Output:
c is:2
c is:3
c is:4
c is:6
c is:7
c is:8
c is:9
sum is =36
|
Pass statement:
- pass statement is used when programmer don’t want to execute a set of code.
- pass statement is null operation. So, nothing will happen when pass statement has been executed.
- Mostly, programmer uses the pass statement when they don’t want to execute the code, but they want the syntactical expressions.
Example:
1 2 3 |
for c in range(1,9): pass |