Go if else statement Tutorial

Udemy Generic 728x90

Definition:

It is the most basic and important feature of all the control flow statements.If is a conditional statement that is used to execute different  sections of code based on different conditions.
Types of If statements:-

  • if statement – Executes block of code only if a condition is true.
  • if…else statement -If a condition is true,executes the block of code.If the condition is false,  else block will execute.
  • if…else if….else statement – Among several blocks only one block(evaluates to true) will execute.

if statement

This statement is used to execute a block of code enclosed in if statement only if a specified condition is true.

Syntax

<br />
 if condition {</p>
<p> // Statements will execute if condition is true</p>
<p>}<br />

Example:-
Find Out the factors of 40.

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    number := 40<br />
    fmt.Print(&quot;The Factors of 40 are:&quot;)<br />
    for i :=1;i &lt;= number;i++ {<br />
        //if remainder is 0 its a factor<br />
        if number % i == 0 {<br />
            fmt.Print(i,&quot; &quot;)<br />
        }<br />
    }<br />
    fmt.Println()<br />
}<br />

Output:

The Factors of 40 are:1 2 4 5 8 10 20 40

if…else statement

This statement is used when you have two options i.e. either this or that. If the if statement is false only then its else block  will execute.

Syntax:

<br />
if condition {</p>
<p>// Statements will execute if condition is true.</p>
<p>} else {</p>
<p>//  Statements will execute if condition is false.</p>
<p>}<br />

Example:
Check the number input by the user from the console is even or odd

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
// Standard input from keyboard<br />
    var inputNumber int<br />
    fmt.Print(&quot;Enter Number:&quot;)<br />
    //input number to check odd or even<br />
    fmt.Scanln(&amp;inputNumber)<br />
    // if true number is even else odd<br />
    if  inputNumber % 2 == 0 {<br />
        fmt.Println(&quot;You Entered:&quot;,inputNumber,&quot;an even number.&quot;)<br />
    }else{<br />
        fmt.Println(&quot;You Entered:&quot;,inputNumber,&quot;an odd number.&quot;)<br />
    }<br />
}<br />

Output:

Enter Number:56
You Entered: 56 an even number.

OR

Enter Number:67
You Entered: 67 an odd number.

If the number entered is divisible by 2 then it is an even number else it is an odd number.

if…else if….else statement

 This block is useful when you have to check multiple conditions and among the several condition blocks,only the selected one will execute.The selected one means whose expression evaluates to true.It is also possible that multiple expression can evaluate to true.In such cases,the first most expression evaluating true will execute.  for eg. if block expression evaluates to true and else if also evaluates to true,In such a condition only the first block will execute according to lexical order i.e. if block.

Syntax:

<br />
if condition {</p>
<p>// Statements will execute if condition is true.</p>
<p>} else if condition {</p>
<p>// Statements will execute if condition is true.</p>
<p>} else {</p>
<p>//  Statements will execute if condition is false.</p>
<p>}<br />

Before understanding the example given below,understand these operators because these operators will play an important role while defining the condition:

Comparison operators

It compares two operands and yield boolean value.

Comparison Operators Meaning
== equal
!= not equal
< less than
<= less than or equal to
> greater than
>= greater than or equal to

Logical operators

Logical operators apply  to two boolean expressions and yield boolean value(true or false).In this case second operand is evaluated only if needed.

Logical Operators Meaning
&& conditional AND
|| conditional OR
! NOT

Example:
Check users  grade after user enters his total marks got by him in five subjects and maximum marks of five subjects.

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    var totalScore int<br />
    var maxMarks int<br />
    fmt.Print(&quot;Enter Your Total marks(best five):&quot;)<br />
    //input total marks obtained<br />
    fmt.Scanln(&amp;totalScore)<br />
    fmt.Print(&quot;Enter maximum total marks of five subjects:&quot;)<br />
    //input maximum marks<br />
    fmt.Scanln(&amp;maxMarks)<br />
    totalScore = (totalScore*100)/maxMarks<br />
    grade := &quot;&quot;<br />
    if totalScore &gt;= 95 {<br />
        grade = &quot;A2&quot;<br />
    } else if totalScore &gt;= 90 {<br />
        grade = &quot;A1&quot;<br />
    } else if totalScore &gt;= 80 {<br />
        grade = &quot;B2&quot;<br />
    } else if totalScore &gt;= 70 {<br />
        grade = &quot;B1&quot;<br />
    } else if totalScore &gt;= 60 {<br />
        grade = &quot;C2&quot;<br />
    } else if totalScore &gt;= 50 {<br />
        grade = &quot;C1&quot;<br />
    } else if totalScore &gt;= 40 {<br />
        grade = &quot;D&quot;<br />
    } else {<br />
        grade = &quot;E&quot;<br />
    }<br />
    fmt.Println(&quot;You got&quot;, grade,&quot;Grade in your exam&quot;)<br />
}<br />

Output:

Enter Your Total marks(best five):414
Enter maximum total marks of five subjects:500
You got B2 Grade in your exam

Here user entered his total marks  (414) and maximum marks (500).then he got his grade i.e. B2. It means the percentage of marks got is between 79 and 90.

Things to remember

  • A string type does not evaluate to boolean by itself while setting any condition.

Look at the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    str := &quot;Hello World!&quot;<br />
    //a string does not evaluate to (boolean)true/false by itself<br />
    if str {<br />
       fmt.Println(str)<br />
    }<br />
}<br />

Output:

# command-line-arguments
./fileName.go:6: non-bool str (type string) used as if condition
  • An integer type does not evaluate to boolean by itself while setting condition.

Look at the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    number :=10<br />
    //an integer does not evaluate to (boolean)true/false by itself<br />
    if number {<br />
        fmt.Println(&quot;number typed:&quot;,number)<br />
    }<br />
}<br />

Output:

# command-line-arguments
./filename.go:6: non-bool number (type int) used as if condition

  • The if keyword, boolean expression and the open curly brace of if block must be in a same line.

Look at the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    number := 40<br />
    fmt.Print(&quot;The Factors of 40 are:&quot;)<br />
    for i :=1;i &lt;= number;i++ {<br />
        if number % i == 0  //open curly brace of if block in next line throw error<br />
        {<br />
            fmt.Print(i,&quot; &quot;)<br />
        }<br />
    }<br />
    fmt.Println()<br />
}<br />

Output:

# command-line-arguments
./factor.go:7: missing condition in if statement
./factor.go:7: number % i == 0 evaluated but not used

  • The closing curly brace of if block,else keyword and its open curly braces must be in a same line

Look at the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    number:=2084<br />
    if  number % 2 == 0 {<br />
        fmt.Println(&quot;Even&quot;)<br />
    } //else part must start from here<br />
    else{ // here it will throw error<br />
        fmt.Println(&quot;Odd&quot;)<br />
    }<br />
}<br />

Output:

# command-line-arguments
./evenOdd.go:8: syntax error: unexpected semicolon or newline before else
./evenOdd.go:11: syntax error: unexpected }
  • Nil value does not evaluate to boolean by itself while setting any condition.

Look at the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
type AgeStruct struct {<br />
    age int<br />
}<br />
func getAgeStruct() *AgeStruct {<br />
    return nil<br />
}<br />
func main() {<br />
    age := getAgeStruct()<br />
    if age { //nil value does not evaluate to boolean expression by itself<br />
        fmt.Println(&quot;Not nil&quot;)<br />
    }else {<br />
        fmt.Println(&quot;nil&quot;)<br />
    }<br />
}<br />

Output:

# command-line-arguments
./nillCheck.go:11: non-bool age (type *AgeStruct) used as if condition
Udemy Generic 728x90

Spread the word. Share this post!