15. break, continue and pass statements

break statement
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
break can be used in while loop and for loop. The statement break is mostly required when because of some external condition, we need to exit from a loop.

Example

for letter in 'Python': 
     if letter == 'h':            
        break
print(letter)
output:
P
y
t
In this program, we iterate through the string "Python" . We check if the letter is 'h', upon which we break from the loop. Hence, we see in our output that all the letters up till 'h' gets printed. After that, the loop terminates.

Continue Statement
This statement is used to tell Python to skip the rest of the statements of the current loop block and to move to next iteration, of the loop. Continue will return back the control to the beginning of the loop. This can also be used with both while and for statement.
Example
for letter in  “Python:
      if letter == 'h':
            continue
print(letter)
will result into
P
y
t
o
n
In this program, we iterate through the string "Python". We check if the letter is 'h', upon which we continue the loop so that 'h' will not be printed. Hence, we see in our output that all the letters up till 'h' gets printed. After that, the loop terminates.

pass statement

Sometimes, it is useful to have a body with no statements, in that case you can use pass statement. Pass statement does nothing.

The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.

However, nothing happens when the pass is executed. It results in no operation (NOP).
We generally use it as a placeholder.

Example:
if condition:
    pass

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.

Example:
for i in range(10):
pass

def function(args):
        pass

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020