go · level 1 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
leaves a loop. skips a round.
break stops a loop straight away, even if it has rounds left. Picture searching your pockets for your keys: once you find them, you stop looking.
continue skips the rest of this round and jumps to the next one. Picture skipping the songs you do not like on a playlist.
Both usually sit inside an if, so they only happen when you want them to.
package main
import "fmt"
func main() {
for n := 1; n <= 10; n++ {
if n == 4 {
break
}
fmt.Println(n)
}
fmt.Println("Stopped at 4.")
} break leaves the loop only, and the program carries on with the line after it.
guess first
One number gets skipped. Which output is right?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
for n := 1; n <= 5; n++ {
if n == 3 {
continue
}
fmt.Println(n)
}
}
your turn
Your turn. Skip a number you do not like.
Pick your least favourite number from 1 to 5. The loop skips it and shows the rest.
output
press run to see what happens
fix it
The keys are in pocket 3. Why keep looking?
output
press run to see what happens
- The keys turn up in pocket 3, but the loop checks pockets 4 and 5 too.
continueonly skips to the next round. You want to leave the loop completely.- Change
continuetobreakon line 7, then press run.
nailed it
you can stop a loop whenever you like. :D
breakleaves a loop straight away.continueskips to the next round.- Put them inside an
ifso they happen at the right time.
new words in your collection
- break
- continue
This lesson isn’t saved. A free account remembers every lesson you finish.