Branching with if and else
if runs a block of code only when its condition is true:
if stok == 0 {
fmt.Println("Barang habis")
}
This prints Barang habis ("out of stock") when stok is zero.
In Go, the condition is not wrapped in parentheses, but the curly braces { } are required — even when the body is just one line.
else and else if
if nilai >= 75 {
fmt.Println("Lulus")
} else if nilai >= 60 {
fmt.Println("Remedial")
} else {
fmt.Println("Tidak lulus")
}
Go checks the conditions from top to bottom and runs the first block whose condition is true (here: pass, remedial, or fail). The rest are skipped.
elsehas to be on the same line as the closing brace}. Puttingelseon a new line causes a compile error.
Comparison operators
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
A comparison always produces a bool. You can compare strings with == and != too.
Task
In an RPG, the color of the hero's health (HP) bar changes with their condition. Complete the function statusHP(hp int) string so it returns:
| Condition | Result |
|---|---|
hp <= 0 | "kalah" |
hp below 30 | "kritis" |
hp below 70 | "terluka" |
| anything else | "sehat" |
(Those are "defeated", "critical", "wounded", and "healthy".)
Example: statusHP(25) → "kritis", statusHP(70) → "sehat".