Choose paths with if and else
Choose paths with if and else
An if statement runs a block only when its condition is true. The condition must be a Boolean expression; Go does not interpret integers or strings as truth values. An optional else block runs when the condition is false.
package main
import "fmt"
func main() { temperature := 28 if temperature >= 25 { fmt.Println("warm") } else { fmt.Println("cool") }}The comparison produces true, so only the first block runs. Braces are required even for one statement. Parentheses around a simple condition are not required. Place else on the same line as the preceding closing brace.
Choose among several paths
package main
import "fmt"
func main() { score := 75 if score >= 90 { fmt.Println("excellent") } else if score >= 60 { fmt.Println("pass") } else { fmt.Println("retry") }}Conditions are checked from top to bottom. Only the first true branch runs; if none is true, the final else runs. Put the narrower high-score condition first: reversing the two thresholds would classify 95 as pass instead of excellent.
Try it locally
Classify balance := -4 as positive, zero or negative. Print exactly one label. Expected: negative. Try again with 0 and 5; predict the output first.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Branching 01: Choose paths with if and else
Check the lesson objective before moving on.
For score 95, which branch runs in the second example?
Which condition is valid for an int count?