Programming/Easy Go

Using Conditional Statements: if / switch

EveryDayIsNewDay 2025. 1. 9. 20:45

In the previous chapter, we learned about "comparison operators" and "logical operators". Programming involves three main steps: receiving input data, processing that data according to the program’s purpose, and outputting the result. In processing data, we often need to compare values and perform actions based on the results.

In real life, You might face situations where you needs to make decisions by comparing different alternatives. For example, Your father told you to take the bus to sun some errands, but you were very hungry. You have five dollars in your pocket that your father gave you to take bus.

Is this a distance I can walk?”, “If I walk, will I be able to run my errands on time?”, “Do I have the strength to walk now?” It will probably give you a lot to think about.

While you're thinking about that, you'll decide whether to eat bowl noodles at the convenience store and walk, or whether to run a quick errand and come home to eat, right?

Similarly, in programming, when there are multiple possible outcomes, we need a way to choose which action to take. The "if" or "switch" statement is used for this purpose in programming.

What is a "statement"?

A "function" is a module used to perform specific tasks, taking inputs, processing them, and returning results. In contrast, "statements" such as conditional statements and loops are commands used inside functions to perform specific actions. Typically, statements are enclosed within a pair of curly braces '{' and '}'.

1. Conditional Statements: if...else

Let's organize the example described above to explain conditional statements: If I can walk the distance, I’ll eat instant noodles and walk; otherwise, I’ll take the bus.

if (I can walk the distance) {     // Condition
     // Execute when the condition is true
     Eat instant noodles at the convenience store;
     Walk;
} else {    // Otherwise
     // Execute when the condition is false
     Take the bus;
}

This can be generalized as follows:

General Format:

if (condition) {
    // Execute commands when the condition is true
    command1;
    command2;
    ...
} else {
    // Execute commands when the condition is false
    command1;
    command2;
    ...
}

The block under "else" is executed if the condition is false. If you only want to execute code when the condition is true, you can omit the "else" block.

Now let's write the following code to see an example of using conditional statements.

package main

import "fmt"

func main() {
	var math_score int = 90
	var english_score int = 89

	if math_score >= 90 {
		fmt.Println("Math study is excellent") // True (Math score is 90 or higher)
	} else {
		fmt.Println("Math study needs a bit more...") // False (Math score is less than 90)
	}

	if english_score >= 90 {
		fmt.Println("English study is excellent") // True (English score is 90 or higher)
	} else {
		fmt.Println("English study needs a bit more...") // False (English score is less than 90)
	}
}
 

After running the code, the output will be as follows:

go run .\condition.go
Math study is excellent
English study needs a bit more...

In the example above, we declare two integer variables, 'math_score' and 'english_score', and initialize them with values 90 and 89, respectively. We then use two conditional statements:

  • 09 : Checks if math_score is greater than or equal to 90
    • since math_score is 90, the condition is true, and " Math study is excellent " is printed
  • 15: Checks if english_score is greater than or equal to 90
    • since english_score is 89, the condition is false, and "English study needs a bit more..." is printed

But what if we need to handle multiple possible outcomes based on a single variable's value?  When we receive our report card at the end of the semester, the results are often expressed as “Excellent,” “Good,” or “Need More” based on the scores, right? If one variable needs to output multiple results depending on the conditions, how should we handle this? We can use multiple conditions in this case. Here's how we can write it using else if.

Multiple Conditional Statements Example:

if (condition 1) {
     // Block to execute if condition 1 is true
} else if (condition 2) {
    // Block to execute if condition 2 is true
} else {
    // Block to execute if neither condition 1 nor condition 2 is true
}
 
Now, let's write the following to see an example using multiple conditional statements.
func main() {
	var math_score int = 73

	if math_score >= 90 {
		fmt.Println("Excellent") // Executes when math_score is 90 or higher
	} else if math_score >= 80 {
		fmt.Println("Good") // Executes when math_score is 80 or higher
	} else if math_score >= 70 {
		fmt.Println("Average") // Executes when math_score is 70 or higher
	} else {
		fmt.Println("Needs effort") // Executes when math_score is less than 70
	}
}
 

The output will be:

Average
  • 06 : Initialize math_score to 73
  • 08 - 16 : The first condition checks if math_score is greater than or equal to 90, but since it’s not, we move to the next condition 'math_score >= 80', which also fails. Finally, the condition 'math_score >= 70' is true, so "Average" is printed.

It's important to note that once a condition is met in the 'if...else if...else' structure, no further conditions are checked, and the program exits the block. If the code were written as below, it would always print "Needs effort"

Incorrect Example:

package main

import "fmt"

func main() {
	var math_score int = 99

	if math_score >= 70 {
		fmt.Println("Average") // Executes when math_score is 90 or higher
	} else if math_score >= 80 {
		fmt.Println("Good") // Executes when math_score is 80 or higher
	} else if math_score >= 90 {
		fmt.Println("Excellent") // Executes when math_score is 70 or higher
	}
}
 
 
In this case, the code would always print "Average" because the first condition math_score >= 70 is true.

Nested Conditional Statements

You could also write the same logic using nested if statements as below, but it makes the code less readable.

package main

import "fmt"

func main() {
	var math_score int = 73

	if math_score >= 90 {
		fmt.Println("Excellent") // Executes when math_score is 90 or higher
	} else {
		if math_score >= 80 {
			fmt.Println("Good") // Executes when math_score is 80 or higher
		} else {
			if math_score >= 70 {
				fmt.Println("Average") // Executes when math_score is 70 or higher
			} else {
				fmt.Println("Needs effort") // Executes when math_score is less than 70
			}
		}
	}
}
 
The program should provide accurate results, but it's also important to write it in a way that others can easily understand. If the program is written in a complex manner, it will be difficult to identify where the problem is when there are errors later on.

 

2. Conditional Statements: switch...case

In addition to 'if...else' and 'if...else if...else', the Go programming language provides the 'switch...case' statement, which compares the value of a variable to certain constants. Here's the syntax:

General Format:

switch (variable) {
    case constant1:   // Executes when variable is equal to constant1
        execution1;
        ...
        executionN;
    case constant2:   // Executes when variable is equal to constant2
        execution1;
        ...
        executionN;
    case constantN:   // Executes when variable is equal to constantN
        execution1;
        ...
        executionN;
    default: // Executes when variable does not match any of the constants
        execution1;
        ...
        executionN
}
 
Let’s look at an example using switch...case.
package main

import "fmt"

func main() {
	var math_grade string = "B"

	switch math_grade {
	case "A":
		fmt.Println("Excellent")
	case "B":
		fmt.Println("Good")
	case "C":
		fmt.Println("Average")
	default:
		fmt.Println("Needs effort")
	}
}

The output will be:

Good
 
The 'switch...case' statement allows comparison between the value of a variable and specific constants. While it does not support comparison using operators like < or >, it is particularly useful when a variable can only take a limited number of specific values.

 

'Programming > Easy Go' 카테고리의 다른 글

Utilizing Loops: for  (0) 2025.01.10
Operators(Arithmetic, Comparison, Logical)  (1) 2024.02.07
Print to Screen  (1) 2024.02.07
Variables and Constants  (0) 2023.09.08
Setup Go development environments  (0) 2023.09.06