The `else if` Keyword
Part of the Fundamentals section of Coddy's GO journey — lesson 36 of 109.
Let's learn how to use the else if keyword in Go to check multiple conditions in sequence. This is useful when you need more than two possible outcomes in your program.
First, let's create a program that categorizes temperature based on different ranges:
temp := 75
if temp < 50 {
fmt.Println("It's cold")
} else if temp < 80 {
fmt.Println("It's pleasant")
} else {
fmt.Println("It's hot")
}After executing this code, the program will show "It's pleasant" on the screen. Here's why: the program first checks if temp (75) is less than 50. Since this is false, it moves to the next condition and checks if temp is less than 80.
Since 75 is indeed less than 80, it executes that code block and prints "It's pleasant". The final else block is skipped because a condition was already met.
The conditions are checked in order from top to bottom, and only the code for the first matching condition runs. Once a condition is met, the remaining conditions are not checked at all.
Challenge
EasyIn this challenge, you'll practice using the else if keyword to handle multiple conditions.
You have a variable weather that contains a string describing the current weather. Your task is to complete the code to print different messages based on the weather condition:
- If it's "sunny", print "Wear sunscreen!"
- If it's "rainy", print "Bring an umbrella!"
- If it's "cold", print "Wear a jacket!"
- For any other weather condition, print "Check the forecast!"
Cheat sheet
Use else if to check multiple conditions in sequence:
temp := 75
if temp < 50 {
fmt.Println("It's cold")
} else if temp < 80 {
fmt.Println("It's pleasant")
} else {
fmt.Println("It's hot")
}Conditions are checked from top to bottom, and only the first matching condition executes. Once a condition is met, the remaining conditions are skipped.
Try it yourself
package main
import "fmt"
func main() {
// This variable contains the current weather condition
weather := "rainy"
// TODO: Complete the if-else if-else statement to print the appropriate message
if weather == "sunny" {
fmt.Println("Wear sunscreen!")
}
// Add your code here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions