The else Statement
The else statement gives your program something to do when the if condition is false. It holds the block of code that runs in that case.
Example
Here time is 20, which is not below 18, so the if condition is false. Go skips that block and runs the else block instead, printing "Good evening.":
Prompt
Use if else to print "Good day." if the time is less than 18, and "Good evening." otherwise.
Set time to 20.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
time := 20
if time < 18 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Example
Now time is 14, which is below 18. The condition is true, so the if block prints "Good day.":
Prompt
Use if else to print "Good day." if the time is less than 18, and "Good evening." otherwise.
Set time to 14.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
time := 14
if time < 18 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Else Statement Syntax
main.go
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Even or Odd
Here is one more use of else: checking whether a number divides evenly by 2. Since 17 leaves a remainder, the else block runs:
Example
Prompt
Use if else and the modulus operator to check if a number is even or odd.
Set the number to 17.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
number := 17
if number % 2 == 0 {
fmt.Println("The number is even.")
} else {
fmt.Println("The number is odd.")
}
}