Conditional Statements and Loops
Learn how to make decisions and repetitions in Go.
Conditional statements
Conditional statements perform various actions based on specific conditions. The developer specifies one or more conditions that the program executes. Particular statements are returned based on the outcome. Go uses logical and comparison operators to create conditions for different decisions. We’re going to explore the following:
- The
if
statement - The
if else
statement - The
else if
statement - The nested
if
statement - The
switch
statement
The if
statement
The if
statement executes a code block only if the specified condition is true
.
Press + to interact
package mainimport ("fmt")func main() {bicycles:= 9tricycles:= 3Username := "Greghu"if bicycles > tricycles {fmt.Println("We have more bicycles than tricycles")}if Username == "Lizzy" {fmt.Println("Elizabeth's username is Lizzy")}// This condition will not print out a result, because it is not true.}
The if else
statement
The if else
statement allows us to run one block of code if the specified condition is true
and another block of code if it’s false
.
Press + to interact
package mainimport ("fmt")func main() {Username := "Greghu"if Username == "Lizzy" {fmt.Println("Elizabeth's username is Lizzy")} else {fmt.Println("Greg's username is", Username)}// Remember starting our else statement on a different line would raise an error.}
The else if
statement
The else if
statement allows us to combine multiple if else
statements.
Press + to interact
package mainimport ("fmt")func main() {Username := "Greghu"if Username == "Lizzy" {fmt.Println("Elizabeth's username is Lizzy")} else if Username == "Greghu" {fmt.Println("Greg's username is", Username)} else {fmt.Println("Ooops, please sign up!")}}
The nested if
The nested if
statement is an if
statement within ...
Access this course and 1400+ top-rated courses and projects.