Continue and Break

  • In this lesson, we will learn how to use the continue and break commands
    • Continue: skips the current loop/iterations that’s running, and proceed to the next loop
    • Break: Completely stops the loop and breaks the code
  • Are usually used when working with for loops

Example #1: Python with the Break Command

Example

Now let’s actually code it!

for i in range (10): 
    if i == 3:
        break
    print (i)
    
0
1
2
for i in range (10): 
    if i == 40:
        break
    print (i)
0
1
2
3
4
5
6
7
8
9

Example #2: Javascript with the Break Command

Example2

Important Notes:

  • i=0 signifies the number that the loop will begin with
  • i < 10 mean that the loop will stop when i reaches the number 10
  • i++ means that the numbers in the loop increase by 1.

%%javascript
for (let i = 0; i < 10; i++)
  for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;
    }
    console.log(i);
}

<IPython.core.display.Javascript object>

Popcorn Hack #1

  • Try making your own break command code using JavaScript! You can use the structure provided above.

Example #3: JavaScript with Continue Commands



%%javascript

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue; 
  }
  console.log(i); 
}

//pretty much the same exact thing as the break commands!
<IPython.core.display.Javascript object>

Popcorn Hack #2

  • Using your knowledge of how to do break commands in Python, try making a simple continue loop in Python!

Hacks/ Homework

  1. Make a break loop in JavaScript, but make the numbers continue by 2 instead of 1. (0, 2, 4, 6, etc)
  2. Make a continue loop in Python, but find out how to change the print command so the output says “This number is…” before the actual number.