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:
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
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.