Go course

ConditionalsBranching with if and else

Go

Display

Theme

Conditionals · Test exercise

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.

else has to be on the same line as the closing brace }. Putting else on a new line causes a compile error.

Comparison operators

OperatorMeaning
==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:

ConditionResult
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".

main.go
package main

import "fmt"

func statusHP(hp int) string {
	// TODO: gunakan if / else if / else
	return "sehat"
}

func main() {
	fmt.Println(statusHP(100))
	fmt.Println(statusHP(25))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)