Skip to main content
Engineering LibreTexts

5.4: Break and Continue

  • Page ID
    117552
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    Learning Objectives

    By the end of this section you should be able to

    • Analyze a loop's execution with break and continue statements.
    • Use break and continue control statements in while and for loops.

    Break

    A break statement is used within a for or a while loop to allow the program execution to exit the loop once a given condition is triggered. A break statement can be used to improve runtime efficiency when further loop execution is not required.

    Ex: A loop that looks for the character "a" in a given string called user_string. The loop below is a regular for loop for going through all the characters of user_string. If the character is found, the break statement takes execution out of the for loop. Since the task has been accomplished, the rest of the for loop execution is bypassed.

        user_string = "This is a string."
        for i in range(len(user_string)):
          if user_string[i] == 'a':
            print("Found at index:", i)
            break
    Checkpoint: Break statement in a while loop
    Infinite loop

    A break statement is an essential part of a loop that does not have a termination condition. A loop without a termination condition is known as an infinite loop. Ex: An infinite loop that counts up starting from 1 and prints the counter's value while the counter's value is less than 10. A break condition is triggered when the counter's value is equal to 10, and hence the program execution exits.

        counter = 1
        while True:
          if counter >= 10:
            break
          print(counter)
          counter += 1
    
    Concepts in Practice \(\PageIndex{1}\): Using a break statement

    What is the following code's output?

    string_val = "Hello World"
    for c in string_val:
      if c == " ":
        break
      print(c)
    1. Hello
      
          
    2. Hello World
    3. H
      e
      l
      l
      o
    Answer

    c. The code prints all characters before the first occurrence of a space character in separate lines. Hence the output is:

    H
    e
    l
    l
    o
    Concepts in Practice \(\PageIndex{2}\): Using a break statement

    Given the following code, how many times does the print statement get executed?

    i = 1
    while True:
      if i%3 == 0 and i%5 == 0:
        print(i)
        break
      i += 1
    1. 0
    2. 1
    3. 15
    Answer

    b. As soon as the print statement is executed, the break statement causes the loop's termination. Also, for i = 15, the condition (i%3 == 0 and i%5 == 0) is met, and hence the print statement will be executed exactly once.

    Concepts in Practice \(\PageIndex{3}\): Using a break statement

    What is the final value of i?

    i = 1
    count = 0
    while True:
      if i%2 == 0 or i%3 == 0:
        count += 1
      if count >= 5:
        print(i)
        break
      i += 1
    
    1. 5
    2. 8
    3. 30
    Answer

    b. The loop finds the first five numbers that are divisible by 2 or 3 . These numbers are 2 , 3 , 4 , 6 , and 8 , and thus 8 is the final i's value.

    Continue

    A continue statement allows for skipping the execution of the remainder of the loop without exiting the loop entirely. A continue statement can be used in a for or a while loop. After the continue statement's execution, the loop expression will be evaluated again and the loop will continue from the loop's expression. A continue statement facilitates the loop's control and readability.

    Checkpoint: Continue statement in a while loop
    Concepts in Practice \(\PageIndex{4}\)

    Given the following code, how many times does the print statement get executed?

    i = 10
    while i >= 0:
      i -= 1
      if i%3 != 0:
        continue
      print(i)
    
    1. 3
    2. 4
    3. 11
    Answer

    b. The print statement is executed for numbers within the range of 0 and 10 (inclusive) that are divisible by 3. The printed output is:

    9
    6
    3
    0
    Concepts in Practice \(\PageIndex{5}\)

    What is the following code's output?

    for c in "hi Ali":
      if c == " ":
        continue
      print(c)
    
    1. h
      i
      
      A
      l
      i
    2. h
      i
      A
      l
      i
    3. hi
      Ali
    Answer

    b. The loop checks whether the character being evaluated is a space character or not. If so, the remainder of the loop will be skipped and the space character will not be printed.

    Try It: Using break control statement in a loop

    Write a program that reads a string value and prints "Found" if the string contains a space character. Else, prints "Not found".

    Interactive Code
    usr = input()
    
    # Printing the given input
    print("You have entered", usr)
    
    # TODO: identify if the string contains a space character
    
    
    
     
    Input

    a string

    Answer

    usr = input()

    # Printing the given input
    print("You have entered", usr)

    found = False

    # Iterating through the string and checking if a space character exists
    for c in usr:
    if c == " ":
    print("Found")
    found = True
    break

    # Printing Not Found otherwise
    if (not found):
    print("Not Found")

    Try It: Using a continue statement in a loop

    Complete the following code so that the program calculates the sum of all the numbers in list my_list that are greater than or equal to 5.

    Interactive Code
    my_list = [1, 5, 7, 12, 5, 17, 9, 2, 4]
    
    total = 0
    
    for i in my_list:
        if i < 5:
            # TO DO: numbers less than 5 should be skipped.
    
       else: 
            # TO DO: numbers greater than 5 should be summed up.
    
    print(total)
     
    Answer

    my_list = [1, 5, 7, 12, 5, 17, 9, 2, 4]

    total = 0

    for i in my_list:
    if i < 5:
    continue
    else:
    total += i

    print(total)


    This page titled 5.4: Break and Continue is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.