Um momento
0x20Lesson 3 of 6

Make decisions with if

Choose different behavior based on a condition.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Use if and else to select a result.

An if statement runs a block only when its condition is true. Add else for the other path. Go does not wrap conditions in parentheses, but braces are required. A short variable declaration can appear before the condition.

main.go
1package main
2
3import "fmt"
4
5func main() {
6    score := 82
7    if score >= 60 {
8        fmt.Println("pass")
9    } else {
10        fmt.Println("try again")
11    }
12}
Output
pass

Conditions evaluate to a bool. Comparison operators include ==, !=, <, <=, >, and >=. Keep the else attached to the closing brace of the if block.

Key takeaways

  • Use if and else to select a result.

  • Go catches many mistakes while compiling.

  • Use small experiments to understand each new language feature.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Go

Write Go in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.

Exercise 1

Label a temperature

+25 XP

Read an integer temperature. Print cold if it is below 15; otherwise print warm.

  • Below threshold
  • At threshold
main.go
Loading editor…

Go is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: