ProgramGuru

if...else Statement

Start with Go if...else Statement

An if...else statement chooses between two paths. Exactly one branch runs for each evaluation of the condition.

What you’ll learn

  • Choose between two exclusive paths.
  • Test boundary conditions.
  • Follow Go’s else formatting rule.

Understand the idea

Use if condition { ... } else { ... } when you want one action for a true condition and another for a false condition. In Go, else follows the closing brace of the if block on the same line.

Only one of the two blocks executes, and then the program continues after the complete statement. This structure is useful for pass/fail decisions, stock availability and simple validation.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for if elseA condition branches into true or false paths before continuing.marks >= 40?TRUEFALSEPrint PassPrint Try againContinue
Trace control flow in the order shown, then compare it with the program.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	marks := 68
	if marks >= 40 {
		fmt.Println("Pass")
	} else {
		fmt.Println("Try again")
	}
	fmt.Println("Result checked")
}

Output

Pass
Result checked

Trace what the program does

The comparison 68 >= 40 is true, so Pass appears. Go skips the else block and then prints Result checked. With 32 marks, the alternative line would be printed.

Avoid common mistakes

  • Avoid writing two separate if statements when the outcomes are mutually exclusive and form one choice.
  • Put else on the same line as the preceding closing brace.

Try it yourself

Change marks to 35 and explain the output. Then test exactly 40 to understand the >= boundary.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How many branches execute in one ordinary if...else statement?
Choose one answer. You can try again.

Answer and explanation

Exactly one branch

Correct. The comparison 68 >= 40 is true, so Pass appears.

What you should remember

You have practiced Go if...else Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: else if Statement →