if, else if, else
- Go course
- Beginner
- Lesson 35/90
- 4 min
Learn conditional branching with if, else if and else in Go.
if, else if, else
In Go, an if condition needs no parentheses but the curly braces are required. The condition must be a bool; a number can't be used directly as a condition.
not := 72
if not >= 85 {
fmt.Println("pekiyi")
} else if not >= 60 {
fmt.Println("geçti")
} else {
fmt.Println("kaldı")
}else must be on the same line as the closing brace.
if with a short statement
if can take a short statement before the condition; a variable declared there exists only within the if-else block. It is used a lot for error checking:
if n, err := strconv.Atoi("42"); err != nil {
fmt.Println("hata:", err)
} else {
fmt.Println(n * 2) // 84
}
// n isn't defined herePractice Grade evaluation
Write degerlendir(not int) string: 85 and above "pekiyi", 60 and above "geçti", otherwise "kaldı". Print degerlendir(90), degerlendir(72) and degerlendir(45) on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func degerlendir(not int) string {
if not >= 85 {
return "pekiyi"
} else if not >= 60 {
return "geçti"
}
return "kaldı"
}
func main() {
fmt.Println(degerlendir(90), degerlendir(72), degerlendir(45))
}Expected output
pekiyi geçti kaldı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>if n { ... }</code> (n an int) compile?
- It compiles
- The condition must be a bool; write n != 0 Correct answer
- Parentheses are missing
- An int can't be used inside an if
Explanation: Go doesn't automatically convert numbers or nil to bool; the comparison is written explicitly.
2 Middle condition
if not >= 85 {
fmt.Println("pekiyi")
} ____ not >= 60 {
fmt.Println("geçti")
}
if not >= 85 {
fmt.Println("pekiyi")
} else if not >= 60 {
fmt.Println("geçti")
}
Explanation: In Go an extra condition is written with else if.
3 Grade and result
| Term | Meaning |
|---|---|
90 |
pekiyi |
72 |
geçti |
45 |
kaldı |
else |
When none is true |