Help with understanding break and continue keywords

I am looking at the definition for break and continue in the loops cheat sheet:
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet

“In a loop, the break keyword escapes the loop, regardless of the iteration number. Once break executes, the program will continue to execute after the loop.”

My understanding, from simply looking at the command and the output, that ‘break’ is iterating through all the items in a list and stops at when an item met the condition set by the if statement. What I don’t understand( and if clarified I will know the language of explaining loops and iterations better), what does escape mean? and Why does it say “the program will continue to execute after the loop”? Shouldn’t it be the program will stop after condition is met and output all items up until that item? Maybe if a definition of what “escape, execute” mean in this context would help. I may have interpret them wrongly. What is meant by “the program will continue to execute after the loop”?

Thanks a bunch.

as shown by the example:

numbers = [0, 254, 2, -1, 3]

for num in numbers:
  if (num < 0):
    print("Negative number detected!")
    break
  print(num)

even though there are more numbers/elements left in the list, the loop has escaped/stopped.

However, if there was code after the loop, that code would still be executed

1 Like

oh okay. Thank you. So if there is say an elif statement after that, then that code will be executed, correct?

no, the loop has been broken. Any code after the loop would execute:

numbers = [0, 254, 2, -1, 3]

for num in numbers:
  if (num < 0):
    print("Negative number detected!")
    break
  print(num)

print("i get here!")
1 Like

break keyword just stops the iteration just after the desired case in an loop is reached, whereas continue , as name suggests continues the loop just leaving the current iteration.

I hope it helps :slight_smile: