Menu
Coddy logo textTech

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 icon

Challenge

Beginner
In this challenge, you'll practice using an if 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.")
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals