0
0
Goprogramming~5 mins

Nested conditional statements in Go

Choose your learning style9 modes available
Introduction

Nested conditional statements help you make decisions inside other decisions. This lets your program check many things step by step.

When you want to check if a number is positive, and then check if it is even or odd.
When you need to decide a price discount based on customer type and purchase amount.
When you want to check if a user is logged in, and then check their role to show different pages.
When you want to check weather conditions and then decide what clothes to wear.
Syntax
Go
if condition1 {
    if condition2 {
        // code if both condition1 and condition2 are true
    } else {
        // code if condition1 is true but condition2 is false
    }
} else {
    // code if condition1 is false
}

Each if or else block can contain another if statement.

Indent your code inside blocks to keep it clear and easy to read.

Examples
This checks if a person is 18 or older, then inside that it checks if they are 21 or older for drinking.
Go
if age >= 18 {
    if age >= 21 {
        fmt.Println("You can drink alcohol in the US.")
    } else {
        fmt.Println("You can vote but not drink alcohol in the US.")
    }
} else {
    fmt.Println("You are too young to vote or drink alcohol.")
}
This checks if a score is passing, then inside that it checks if the score is excellent.
Go
if score >= 50 {
    if score >= 90 {
        fmt.Println("Grade: A")
    } else {
        fmt.Println("Grade: Pass")
    }
} else {
    fmt.Println("Grade: Fail")
}
Sample Program

This program checks a person's age. It first checks if the person is 18 or older. If yes, it then checks if the person is 21 or older to decide what message to print.

Go
package main

import "fmt"

func main() {
    age := 20

    if age >= 18 {
        if age >= 21 {
            fmt.Println("You can drink alcohol in the US.")
        } else {
            fmt.Println("You can vote but not drink alcohol in the US.")
        }
    } else {
        fmt.Println("You are too young to vote or drink alcohol.")
    }
}
OutputSuccess
Important Notes

Remember to use curly braces {} to group your code blocks.

Nested conditions can get hard to read if too deep. Try to keep them simple.

Summary

Nested conditionals let you check one condition inside another.

Use them to make detailed decisions step by step.

Keep your code clean and well indented for easy reading.