Javascript required
Skip to content Skip to sidebar Skip to footer

What Does a Continue Statement Do Pyhton

Overview

break, pass, and continue statements are provided in Python to handle instances where you need to escape a loop fully when an external condition is triggered or when you want to bypass a section of the loop and begin the next iteration. These statements can also help you gain better control of your loop.

Scope

  • In this article, we will learn about the break, pass, and continue statements with their syntaxes, use cases, and suitable examples.
  • We will also look at the functioning of break, pass, and continue statements with the help of proper flow charts and diagrams.

Break Statement in Python

Python provides us with a particular purpose statement – break. It is worth noting that the break statement can only be used within the for and while loops. Once the program encounters the break statement, it terminates the loop immediately, and the lines of code written right after the body of the loop continue to execute.

The break statement will cause the loop to end even if the while loop condition evaluates to True, or in the case of for loop. It will cause the control of the program to jump out of the for loop even if it satisfies the condition.

A typical example of when the break statement is used is during a sequential search. For example, you're searching for an element in a list of elements using a for a loop. You will add in a comparison condition, to check if the element is found. If the element is found, then you would exit from the loop without traversing the remaining elements.

Here is a flowchart of how the break statement works to give you better clarity.

Break Statement in Python

Syntax of Break Statement in Python

The syntax is pretty simple, you just have to put in the keyword break when you want the loop to terminate. Let's look at some pseudo-code.

Syntax of Break Statement in Python

The above pseudo-code is for the for loop.

Break Statement in Python - While loop

The above pseudo-code is for the while loop.

Implementation of Break Statement in Python

Now that we know what the break keyword is, what it does and how to use it, let us look at some more examples.

Let's say we want to write a program that is set to print the first seven items in a list, but if it encounters the number '4', we need to exit the loop. We can easily do this using the break statement.

Example:

            
                                  nums = [                  7                  ,                                    2                  ,                                    3                  ,                                    1                  ,                                    5                  ,                                    4                  ,                                    6                  ,                                    8                  ,                                    9                  ]                                    count =                                    0                                                                        while                                      count <                                    7                  :                                                                        print                  (nums[count])                                                        count +=                                    1                                                                                          if                                      nums[count] ==                                    4                  :                                                                        break                                                                        print                  (                  "End"                  )                                                

Output:

          

Explanation:

Now in this program, we added a condition wherein if we encounter the number 4, we need to break the loop. And since we encountered a 4, the loop breaks immediately.

What if there was no 4?

Example:

            
                                  nums = [                  1                  ,                                    2                  ,                                    3                  ,                                    5                  ,                                    6                  ,                                    7                  ,                                    8                  ,                                    9                  ]                                    count =                                    0                                                                        while                                      count <                                    7                  :                                                                        print                  (nums[count])                                                        count +=                                    1                                                                                          if                                      nums[count] ==                                    4                  :                                                                        break                                                                        print                  (                  "End"                  )                                                

Output:

          

Since the program did not encounter any 4, the control does not jump out of the loop, and the loop continues to run.

What if the break statement is used in a nested loop? In that case, the break statement will cause the program to jump out of the loop that the break statement is part of and move the control to the first line after the body of the loop containing break. If it was used in the outermost loop itself, it would exit the loops and move directly to any statements written outside the loops and continue executing the program.

Example:

            
                                  l1 = [                  1                  ,                                    2                  ,                                    3                  ]                                    l2 = [                  'a'                  ,                                    'b'                  ,                                    'c'                  ]                                                      for                                      num                                    in                                      l1:                                                                        for                                      ch                                    in                                      l2:                                                                        print                  (num, ch)                                                                        if                                      num ==                                    2                                                      and                                      ch ==                                    'b'                                      :                                                                        print                  (                  'BREAK'                  )                                                                        break                                                                  

Output:

            
                                  1                                      a                                                      1                                      b                                                      1                                      c                                                      2                                      a                                                      2                                      b                  BREAK                                    3                                      a                                                      3                                      b                                                      3                                      c                                                

That's all for the break statement!

Pass Statement in Python

Let's now talk about doing nothing in Python. Seems odd? But yes, the pass statement does nothing. For doing nothing, it's a pretty useful statement. The syntax of the pass statement is the same as a break.

Why do we Use Pass Statement?

To do nothing inside a block of code, you can use the pass statement.

Example:

            
                                  if                                                      1                                      +                                    2                                      ==                                    3                  :                                                                        print                  (                  "Correct math"                  )                                                                        pass                                                                                          print                  (                  "This will also be printed."                  )                                                

Output:

            
                                  Correct math                  This will also be printed.                              

But this doesn't seem useful, does it? Not writing the pass statement there wouldn't make any difference in the code, and it would also make the code shorter. Why does the python syntax have a statement that tells the interpreter to do nothing?

The statement can be used to fulfill a place in a block of code that needs at least 1 statement.

Example:

          

You have this piece of code, and you really do not know at this point of time, what the values of a and b will be, and what you will be doing if the condition evaluates to True. You want to leave the body empty, but you cannot do that because just running this piece of code would give you an indentation error. Why? Because after the colon (:), Python expects an indented block of code, even if it is a single line or a single statement.

Here, we can make use of the pass statement.

          

Thanks to the pass statement, we won't be receiving any errors.

There are more uses of the pass statement, some temporary and some permanent.

Temporary Uses of Pass Statement

The pass statement can be used to fill in code initially that could be used in the future. It may sound silly to use the pass statement in parts of the code that would be deleted anyway later, but it proves to be very useful in the initial stages of development for faster development.

Example:

Say you have a function to do a task that calls another function. But the problem here is that you don't know how the function you're calling works. So, you use the pass statement.

            
                                  def                                                      fun1                  (                  args                  ):                                                                                          # some code                                                      fun2():                                                      # some more code                                                                                          return                                      values                                                      def                                                      fun2                  (                  args2                  ):                                                                                          pass                                                      # TODO                                                                  

This function, func2, doesn't do anything right now, but it lets you run and test fun1 without any errors.

Another use case for the pass statement is when you just want to understand the structure of the code before going into its complexities.

Example:

In a FizzBuzz code ( a game in which you start from 1, count to 100, and say "Fizz", if the number is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if the number is divisible by both 3 and 5 ):

            
                                  if                                      num %                                    15                  :                                                                        pass                                                                        elif                                      num %                                    3                                      :                                                                        pass                                                                        elif                                      num %                                    5                  :                                                                        pass                                                                        else                  :                                                                        pass                                                                  

This helps you understand the structure of the code before you go into the if -elif statements to complete the code.

These are a few temporary uses of the pass statement. It also has permanent use cases like :

1. Exception Catching:

In python, we use the tryexcept block for handling errors. Sometimes, you might not want to do anything upon encountering an error. In that case, you can use the pass statement. Let me show you an example.

            
                                  def                                                      ensure_nonexistence                  (                  filename                  ):                                                                                          try                  :                                    os.remove(filename)                                                      except                                      FileNotFoundError:                                                                        pass                                                                  

This function above removes the file mentioned and does not fail if the file does not exist. If the file you want to remove does not exist, you need not do anything. So when the FileNotFoundError is raised, you can simply use the pass statement.

2. If…Elif Chains

Say in an interview, you're asked a basic FizzBuzz question, except with a little twist. If the input number is divisible by 3, print Fizz. If divisible by 5, print Buzz. If divisible by 15, print nothing, and if divisible by 20, print Twist.

            
                                  for                                      num                                    in                                                      range                  (                  100                  ):                                                                        if                                      num %                                    20                                      ==                                    0                  :                                                                        print                  (                  "Twist"                  )                                                                        elif                                      num %                                    15                                      ==                                    0                  :                                                                        pass                                                                                          elif                                      num %                                    5                                      ==                                    0                  :                                                                        print                  (                  "Buzz"                  )                                                                        elif                                      num %                                    3                                      ==                                    0                  :                                                                        print                  (                  "Fizz"                  )                                                                        else                  :                                                                        print                  (num)                                                

Clearly we can see that the use of the pass statement allows you to avoid refactoring the logic. You are also able to structure the code according to its description.

Continue Statement in Python

Continue is also one of the useful loop control statements in python. It is almost the opposite of the break statement discussed above. Break terminates the loop, and the continue statement forces the program to execute the next iteration of the loop.

When the program control encounters the continue statement, the code following the continue statement (if any) will be skipped, and the next iteration of the loop will begin.

Continue Statement in Python

We can understand the use of the continue statement with an example.

            
                                  for                                      letter                                    in                                                      'python'                  :                                                                        if                                      letter ==                                    'o'                  :                                                                        continue                                                                                          print                  (letter)                                                

As we can see in the code above, the code after the continue statement does not get executed, hence omitting the print statement when the letter 'o' is encountered. We directly move to the next iteration of the loop.

Of course, the above code could have been written in various other ways without using the continue statement. Let us understand its importance in readability and how it reduces expensive run time with an example.

You have two lists, x, and y. You'd like to zip (a function that generates an iterator of a series of tuples) them and perform some functions on them depending upon two values of a and b, which belong to the result of zip.

Here's some code without the continue statement. Notice how it looks all over the place with nested if statements, decreasing the readability.

            
                                  for                                      a, b                                    in                                                      zip                  (x, y):                                                                        if                                      a > b:                                    c = calculate_c(a, b)                                                      if                                      b - c < a:                                                        b =                                    min                  (b, c)                                                                        if                                      a **                                    2                                      - b **                                    2                                      >                                    0                  :                                    lots()                                   of()                                   code()                                   here()                              

Now here, the nested if statements might make the code look confusing. Watch how the continue statement helps make this code better :

            
                                  for                                      a, b                                    in                                                      zip                  (x, y):                                                                        if                                      a <= b:                                                                        continue                                                      c = calculate_c(a, b)                                                      if                                      b - c >= a:                                                                        continue                                                                          b =                                    min                  (b, c)                                                                        if                                      a **                                    2                                      - b **                                    2                                      <=                                    0                  :                                                                        continue                                                      lots()                       of()                       code()                       here()                              

Notice how this is more readable and convenient to write?

Conclusion

  1. Break, Pass, and Continue statements are loop controls used in python.
  2. The break statement, as the name suggests, breaks the loop and moves the program control to the block of code after the loop (if any).
  3. The pass statement is used to do nothing.
    • Two of its uses are :
      • Exception Catching
      • If elif chains
  4. The continue statement is the opposite of the break statement and is used to force the next iteration of the loop. Any lines of code after the continue statement in the loop will not be executed.

mackaread1979.blogspot.com

Source: https://www.scaler.com/topics/python/break-pass-and-continue-statement-in-python/