Break and Continue

05 min read

Break and continue statements are used to alter the normal flow in the loop based on the requirements of the program.

Break statement, when used terminates the loop having it and exits the loop with the values of the latest iteration. The program after the exited loop is executed normally till the end of the program. If a break statement is used inside a complexly nested loop, it terminates only the innermost loop in which it is contained. 

Syntax for break

for value in sequence:
if value = True:
break
print()

 

Let us discuss break statement with an example for better understanding.
Task: Print the letters in "FACEPREP" one by one untill the letter R is reached using break statement in Python.

for letter in "FACEPREP":   # letter is a variable which could have been with any name. each iteration the letter is advanced in the string "FACEPREP" and stored in variable letter.
if letter == "R": #check for condition
break # if condition true, then break out of the loop and print the final print statement.
print(letter) # if condition false, then print that letter.
print('untill letter R printed') #once the for loop is terminated, print this.

# Note: observe the indentations carefully
Output:
F
A
C
E
P
until letter R printed.

 

Continue: This is another statement which could alter the normal course of the loop. When a continue statement is executed the loop skips the rest of the code in
that iteration inside the loop. Loop is not terminated but the loop continues with the next iteration.

Task: write a program to skip all "E"s in a given string "FACEPREP"

for letters in "FACEPREP": # for every letter in FACEPREP
if letters == "E": # if letter is E, then skip printing the letter and go to the next iteration with the next alphabet
continue #Remember that loop is not terminated like break statement.
print(letters)

print("The end")
Output:
F
A
C
P
R
P
The end

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error