The `if` Statement
Part of the Fundamentals section of Coddy's GO journey — lesson 34 of 109.
The if statement lets your program make decisions based on conditions. It executes code only when a condition is true.
Let's create a simple program that uses an if statement to check someone's age:
age := 18
if age >= 18 {
fmt.Println("You are an adult")
}After executing this code, the program checks if the age variable is greater than or equal to 18. Since 18 is equal to 18, the condition is true, and the message "You are an adult" will show on the screen.
The code inside the curly braces only runs when the condition evaluates to true. If the age was less than 18, nothing would be printed.
Challenge
Beginnerif statement in Go. We have a variable temperature with a value of 25. Your task is to write an if statement that checks if the temperature is greater than 20. If it is, print "It's warm today!"Cheat sheet
The if statement executes code only when a condition is true:
age := 18
if age >= 18 {
fmt.Println("You are an adult")
}The code inside the curly braces only runs when the condition evaluates to true. If the condition is false, nothing happens.
Try it yourself
package main
import "fmt"
func main() {
// This variable represents the temperature in Celsius
temperature := 25
// TODO: Write an if statement that checks if temperature is greater than 20
// If true, print "It's warm today!"
fmt.Println("Weather check complete.")
}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