go · level 1 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
is the other path at the fork.
An if on its own either runs its block or skips it. Often you want a plan B. else means otherwise: when the condition is false, Go runs the else block instead.
At a fork you always take exactly one path. With if and else, exactly one block runs. Never both, and never neither.
Write } else { all on one line: close the if block, say else, then open the new block. Put else on a line of its own and Go cannot read it.
package main
import "fmt"
func main() {
biscuits := 0
if biscuits == 0 {
fmt.Println("Time to go to the shop.")
} else {
fmt.Println("Have a biscuit!")
}
} Read else as "otherwise".
guess first
Comic or savings? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
coins := 3
if coins == 5 {
fmt.Println("Buy the comic.")
} else {
fmt.Println("Keep saving.")
}
fmt.Println("Coins:", coins)
}
your turn
Your turn. Meet a pet that is not a dog.
Type any pet except a dog between the quotes, then press run to see plan B.
output
press run to see what happens
fix it
The cinema code will not run. Fix it!
output
press run to see what happens
- Go is unhappy with line 8. Look at where
elsesits. elsemust sit on the same line as the}that closes theifblock.- Join lines 7 and 8 so they read } else {, then press run.
nailed it
your program has a plan b now. :D
elseruns when theifcondition isfalse.- Only one block runs: the
ifblock or theelseblock. - Write
} else {together on one line.
new words in your collection
- else
This lesson isn’t saved. A free account remembers every lesson you finish.