Control statements(Break, Continue, Pass) in Python.

Control Statement

Control statement allow a programmer to control the flow of program according to their need. Control statements are break, continue and pass.

Break Statement

The break statement allow a programmer to terminate a loop, when the break statement is encountered inside the loop,the loop is immidiately terminated and program control automatically goes to first statement.

Break statement in while loop

Syntax: while test_condition: statement(s) if test_condition: break statement(s)

Break statement in for loop

Syntax: for variable_name in Sequence: //Loop_Body if test_condition: break //Loop_Body //Statement after Loop

Write a program to demonstrate the use of break statement.

Syntax: print("The number from 1 to 5") for num in range(1,100): if num==4: break else: print(num)

output

The number from 1 to 5 1 2 3

Continue Statement

The continue Statement is exactly opposite to the break statement, Continue statement is encountered within a loop the remaining statement within the body are skipped but the loop condition checked to see if the loop should continue or exit.

Continue statement in while loop

Syntax: while test_condition: statement(s) if test_condition: continue statement(s)

Continue statement in for loop

Syntax: for variable_name in Sequence: //Loop_Body if test_condition: continue //Loop_Body //Statement after Loop

Write a program to demonstrate the use of continue statement.

Syntax: print("The number from 1 to 5") for num in range(1,6): if num==4: continue else: print(num)

output

The number from 1 to 5 1 2 3 5

Pass Statement

Pass statement is used to give a empty loop to a program. We are using pass statement for empty control statement.

Example:

st="Python" for i in st: pass print("Last Letter is ",i)

output

Last Letter is n

Comments

Popular posts from this blog

Introduction to Python.

Decision Making Statement.