Frequently Asked Questions

What is break, continue and pass in Python?

In Python, the break and continue keywords can be used to alter the flow of a loop.
Loops are used to iterate over a block of code until the test expression becomes false. But there may be a case where we wish to terminate the iteration in between. The break and continue are used for this task.
But how are they different from each other? Let’s look at their code individually.
break
The break statement terminates the complete loop and the control of the program flows to the statement immediately after the loop body.

for val in "varsha":
   if val == "s":
        break
   print(val)
print("Loop Terminated")

In the above code, we iterate through the string “varsha”. We check if the letter is “s”, we will use a break statement to terminate the loop. The control of the program reaches the line print(“Loop Terminated”).
If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.
continue

Unlike the break, the continue statement skips only the current iteration. The loop doesn’t terminate but continues on with the next iteration.

We will use the same code as above to understand the difference between break and continue. Just replace the break keyword with continue.

for val in "varsha":
   if val == "s":
       continue
   print(val)

In the above code, only the iteration where val is s is skipped.

pass

The pass is used to fill up the empty blocks of code which need to be executed during runtime but don’t have any code written yet.

For example, let there be a function func() whose functionality is yet not decided.

## If we leave func() empty and call it, it will throw an error.


def func():

 

 

 

 

## pass can be used in such cases

def func():
    pass

pass represents a null operation.

 

Other Popular Questions