In the previous lesson, we learned how to execute code when a condition is true. But what if we want to do something different when the condition is false? That's where the else statement comes in.
The else statement provides an alternative block of code that executes when the if condition is false.
powerLevel := 5000
if powerLevel > 9000 {
fmt.Println("It's over 9000!!!")
} else {
fmt.Println("It's not that impressive...")
}
// Output: It's not that impressive...
In this example, since 5000 is not greater than 9000, the condition is false, so the code in the else block executes instead.
Think of if-else as a fork in the road - your program will take one path or the other, but never both.
temperature := 15
if temperature > 25 {
fmt.Println("It's hot outside!")
} else {
fmt.Println("It's not hot outside.")
}
// Output: It's not hot outside.
The else block only runs when the if condition evaluates to false. It's guaranteed that exactly one of the two blocks will execute.
func checkStock(quantity int) {
if quantity > 0 {
fmt.Println("In stock")
} else {
fmt.Println("Out of stock")
}
}
checkStock(10) // Prints: In stock
checkStock(0) // Prints: Out of stock
Building on the previous lesson, you'll now extend the checkPowerLevel function to handle both cases.
Modify the function so that:
powerLevel is greater than 9000, print "It's over 9000!!!"powerLevel is less than or equal to 9000), print "Meh, it's only followed by the power level valueThe function signature remains the same:
func checkPowerLevel(powerLevel uint) {
// Your code here
if powerLevel > 9000 {
fmt.Println("It's over 9000!!!")
}
}