Making Decisions

Making Decisions

Making Decisions

Your code needs to make choices. An if statement runs a block of code only when a condition is true:

example.go
if temperature > 35 {
    fmt.Println("Too hot")
}

If temperature is 40, the condition temperature > 35 is true, so the code inside the braces runs. If temperature is 20, the condition is false and the block is skipped entirely.

> leaves out exactly 35. >= includes it, so "35 or above" needs >=. <= does the same for "35 or below".

You can add an else block that runs when the condition is false:

example.go
if temperature > 35 {
    fmt.Println("Too hot")
} else {
    fmt.Println("Not too hot")
}

For multiple conditions, chain them with else if. Go evaluates top to bottom and runs the first block that matches:

example.go
if latencyMs < 100 {
    fmt.Println("fast")
} else if latencyMs < 500 {
    fmt.Println("acceptable")
} else {
    fmt.Println("slow")
}

A 250ms response skips the first check because it is not under 100. It matches the second check, so Go prints "acceptable" and skips the rest.

A Few Things to Notice

No parentheses around the condition (unlike most languages), and the braces {} are mandatory, even for one-liners.

else and else if must go on the same line as the closing }:

example.go
}               // ❌ syntax error
else if ... {

} else if ... { // ✅

Go auto-inserts a semicolon at the end of a line, so else on its own line ends the if before Go sees it.

Setting a Variable Inside a Branch

When a variable is declared before the if, assign to it inside the branches with =, not :=:

example.go
category := ""
if status >= 500 {
    category = "server error"   // = assigns to the category above
}

Writing := inside the if makes a new variable that only lives until the closing }, so the outer one stays "". If nothing reads the new variable, Go refuses to compile with declared and not used.

>_Exercise

Exercise: Grade Calculator

Fill in the if/else if/else block inside getGrade to check the score parameter and set grade to the correct letter:

  • score 90 or above → "A"
  • score 80 or above → "B"
  • score 70 or above → "C"
  • score 60 or above → "D"
  • score below 60 → "F"

When main runs, it should print:

output
A B C D F
Stuck? Reveal a hint to help you.
Hints (0/5)
Key Takeaway
Next UpCombining conditions with logical operators.