Conditions if/else.¶
Objective¶
To understand if/else conditions.
If/else conditions are of very fundamental importance to programming and are present in all the programming languages.
The intent of condition is very simple
1 2 3 4 5 |
|
Structure¶
Navigate to our code folder
1 |
|
For our program create a new folder '07_if_else'
1 |
|
And lets create a file 'if_else.go' in it, finally the structure would look like this:
1 |
|
Code¶
The code will be divided into two parts
1.
if/else condition
package main
import "fmt"
func main() {
d := "Dog"
c := "Cat"
// checking the value of variables
if d == "Dog" {
fmt.Println("Woff")
} else {
fmt.Println("I don't know which animal!")
}
Review
on line 10 we check if the value of the variable "d" is equal to "Dog"
1 |
|
If the condition is true then we print out "Woff"
1 |
|
If the condition is false, we print "I don't know which animal"
1 |
|
- If/else statements can also be chained if you have multiple conditions
if/else condition
16 // You can also chain if / else conditions
17 if c == "monkey" {
18 fmt.Println("I am a monkey.")
19 } else if c == "Dog" {
20 fmt.Println("I am a dog.")
21 } else if c == "Cat" {
22 fmt.Println("Meoww")
23 }
24 }
Review
On line 17 we check if value of the variable "c" is "monkey", if the conditions evaluates to true then we print "I am a monkey"
1 |
|
If it evaluates to false then we check it once again if it contains the value of "Dog"
1 |
|
Since, this also evaluates to false, we check for the next condition
1 |
|
As it evaluates to true, we print out "Meoww" on the screen
1 |
|
In case if "c" does not evaluate to true in any of the case, nothing will be printed.
Running your code¶
Open your terminal and navigate to our folder
1 |
|
Once in the folder type the following command
1 |
|
Output¶
Output
1 2 |
|
Note¶
Strings in Go are case sensitive, "monkey" and "Monkey" are evaluated differently, so be sure of using the right case when checking for evaluation.
Github¶
Just in case you have some errors with your code, you can check out the code at github repo
Golang Playground¶
You can also run the code at playground
Next¶
We will see for loops.