Python: break Loop Control Statement


The flow inside looping statements are controlled using the looping control statements like pass, break and continue.

When we want to stop a loop or break away from it we can use break statement.

Example

Go through the below code, Assume A – Adult passenger, C- Child, FC – Flight Captain, FA – Flight Attendant, SP – Suspicious passenger.

for pasngr in "A","A", "FC", "C", "FA", "SP", "A", "A":
	if(pasngr=="FC" or pasngr=="FA"):
	   print("No check required")
	     continue
	
	if(pasngr=="SP"):
	    print("Declare emergency in the airport")
	    break	
	if(pasngr=="A" or pasngr=="C"):
	    print("Proceed with normal security check")
print("Check the person")
print("Check for cabin baggage")


Output

Proceed with normal security check
Check the person
Check for cabin baggage
Proceed with normal security check
Check the person
Check for cabin baggage
No check required
Proceed with normal security check
Check the person
Check for cabin baggage
No check required
Declare emergency in the airport

In this above example, if you will see when value of passenger is FC or FA then it will execute the statement inside the if block because it’s having continue keyword the the next statement after continue will skip and pointer will reach to next value of for loop.

Same as when passenger will value will be SP then this block having break keyword, it will terminate the loop and stop execution inside the loop and pointer will directly jump to next statement after loop.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s