0
0
Goprogramming~5 mins

Why conditional logic is needed in Go

Choose your learning style9 modes available
Introduction

Conditional logic helps a program make decisions. It lets the program choose what to do based on different situations.

When you want to check if a user entered the correct password.
When you want to give a discount only if the customer buys more than 5 items.
When you want to show a message only if it is morning.
When you want to stop a game if the player loses all lives.
When you want to perform different actions based on user input.
Syntax
Go
if condition {
    // code to run if condition is true
} else {
    // code to run if condition is false
}

The if keyword checks a condition.

The else part runs if the if condition is false.

Examples
This checks if age is 18 or more. It prints a message based on that.
Go
if age >= 18 {
    fmt.Println("You can vote.")
} else {
    fmt.Println("You are too young to vote.")
}
This runs code only if the score is above 90.
Go
if score > 90 {
    fmt.Println("Great job!")
}
Sample Program

This program checks the temperature. It prints if it is hot or not.

Go
package main

import "fmt"

func main() {
    temperature := 30
    if temperature > 25 {
        fmt.Println("It's hot outside.")
    } else {
        fmt.Println("It's not hot today.")
    }
}
OutputSuccess
Important Notes

Always make sure your conditions are clear and simple.

You can use multiple if and else if to check many conditions.

Summary

Conditional logic lets programs make choices.

Use if and else to run code based on conditions.

This helps programs react differently in different situations.