What You are Going to Learn

In the last lesson we introduced the concept of selection. Selection is how a computer program makes a decision.

In this lesson we want to extend the concept to selection to show you how a computer program can make a choice between two or more alternatives.

How to do Something else

So far we have showed you how to use selection statements to make decision in your programs. Go calls selection statements if statements. But this is only part of the story of selection.

You can achieve a huge amount with just if statements and variables. But sometimes you want something more. Sometimes you want to do one thing if the condition in the if statement is true, but a completely different thing if the condition is false.

You can do this already, you just need to use two if statements like this:

if number > 10 {
    fmt.Println("The number is greater than 10")
}
if number <= 10 {
    fmt.Println("The number is less than or equal to 10")
}

Now it is your turn

Think about this carefully for a minute. Can you work out what happens if number had the values 5, 10, 15? Is it possible for both of the conditions to be true at the same time?

If the value of number is 5 or 10 then only the second condition is true. So the output would be

The number is less than or equal to 10

If number is 15 then only the first condition is true and the output is

The number is greater than 10

Both conditions cannot be true at the same time. The conditions are the opposite of each other.

There is an easier way to do this. It’s called an if else statement and that is what you are going to learn about in this lesson.

Important

Make sure you have completed the last lesson about selection before you try this lesson. You will need to understand selection and if statements first.

Selection

Before we get to if else statements lets look back at selection and if statements. The if else statement is an extension of the if statement so you need to know how if statements work first.

Now it is your turn

Can you remember what these operators mean?

==
<<=
>>=

If you type an if statement in a computer program what will the answers be?

Look at this if statement

if temperature = 100
    fmt.Println("The water is boiling.")
fmt.Println("The water is getting hotter.")

How many mistakes can you find?

==equals to
<less than
<=less than or equal to
>greater than
>=greater than or equal to

Note that double equals sign, == is used for equals to. A single equals sign is already used in Go for variable assignment.

A computer program can only answer true or false to an if statement. This means that you have to ask a very precise question.

The if statement

if temperature = 100
    fmt.Println("The water is boiling.")
fmt.Println("The water is getting hotter.")

has three mistakes in it. The first two mistakes are the missing opening and closing braces, the { and } that should surround the line

fmt.Println("The water is boiling.")

The last mistake is more subtle. The if statement does not contain a valid condition, it contains a variable assignment. The single equals sign, = in

if temperature = 100

should be replaced with a double equals sign, ==, to test for equivalence.

The corrected if statement would therefore be

if temperature == 100 {
    fmt.Println("The water is boiling.")
}
fmt.Println("The water is getting hotter.")

Tip

Remember that you always need the braces, the { and } in the if statement. They are important to Go because they mark a block of statements that Go should execute if the condition is true.

Remember that you have to type == to mean equals to!

What is the answer when you compare values?

Let’s start with something simple. What is the answer to this?

12 <= 34
The question is 12 less than or equal to 34. The answer can only be yes or no, or more correctly true or false.

The concept of true and false, or yes and no, or one and zero so common in computing that it has its own type. The type is known as a boolean type, named after the 19th century mathematician George Boole. Who first described how addition could be described using sets. This has its realisation in computer science as boolean algebra.

Go expresses the boolean type as a type called bool. Variables of type bool can be created using the same variable declaration pattern as other variables. Likewise values can be assignvalueed to variables of type bool using the variable assignment pattern. You can only assign the values true or false or the result of a comparison to a variable of type bool.

To show you what we mean look at this

1var answer bool
2answer = 12 <= 34
3if answer == true {
4    fmt.Println("12 is less than or equal to 34")
5}

The result of the comparison of 12 <= 34 is a boolean value and is assigned to the variable answer in line 2. The answer variable is declared as a bool type in line 1.

But, there is a slightly simpler way to write this: the if test can be reduced to this

1var answer bool
2answer = 12 <= 34
3if answer {
4    fmt.Println("12 is less than or equal to 34")
5}

The equivalence test of answer against the value true is unnecessary. The if statement will test the condition. If the condition happens to be a boolean variable then the test against true or false is implicit in the meaning of the if statement itself. There is no need to write the test explicitly.

Okay, but ‘so what?’ you might be thinking: why would you want to do this? Sometimes it’s necessary, or just simpler, to calculate the value of a condition and store the result in a boolean variable for later use. Examples of this approach would be used in repetition, which we will show in later lessons, or to test the conditions necessary to exit a program early.

Logical Opposites

What is the opposite of true? What is the opposite of false?

The answer is

False is the opposite of true

True is the opposite of false

These are the logical opposites of each other. This is called negation.

Negation is a really common in computer programs. We’ll show you an example in a minute. But it is so common Go has a special symbol for it.

The symbol Go used to logically negate a boolean variable is ! You can use this symbol in front of variables or expressions. If the value of the variable or expression was true then the ! makes it false. If the value was true then ! makes it false.

For example

1var answer bool
2var negatedAnswer bool
3answer = true
4negatedAnswer = !answer

This can also be used in if statements. This is typically how you would use negation.

1var locked bool
2locked = IsTheDoorLocked()
3if !locked {
4    fmt.Println("The door is open")
5}

If you do not have a function called IsTheDoorUnlocked() available then you can work this out by negating the answer that IsTheDoorLocked() returns.

If the door is locked, it must be closed. If the door is unlocked the negation or negation of locked then it must be open.

So you don’t need a function called IsTheDoorUnlocked at all!

What if you want to tell if things are unequal?

Negation has another use. You can use it to tell if two numbers are different. This won’t tell you which number is bigger or smaller only that the numbers are different.

To do this you need to use a combination of an equals test and negation. Like this.

!(first_number == second_number)

If you want to tell if the numbers first-number and second-number are different then you can first test them for equality, using a == operator. If the numbers are different the result of the equality test is false.

But we want to test for difference. So when the numbers are different we want the answer to be true. This can be achieved if we negate the answer of the equality test with the ! symbol at the start of the expression.

Important

The brackets are required because we want to negate the answer of the equality operator, the == so we need this to happen first. The negation operator, ! has a higher precedence then the == operator.

It works, but it is a lot to type! The good news is Go provides a better way to do this. It is called the not equals to operator, typed !=.

If the number on the left of the != operator is different from the number on the right the result is true. Otherwise it is false.

Comparing Strings

One last thing before we get back to if else statements and that is comparing strings. The good news is that if you can compare numbers you can already compare strings. It is exactly the same.

String comparison uses the same set of comparison operators as numbers. The meaning of each operator, <, <=, ==, !=, >=, > is the same as for numbers.

Strings are equal if they have the same sequence of runes (letters, punctuation symbols etc. ) and have the same number of runes. Otherwise the strings are not equal.

The not equals, !=, operator also works when comparing two strings. If the strings are not the same length or any letter in the two strings is different the != operator returns true. Otherwise the result is false

Strings are ordered alphabetically i.e. dictionary order. Or more correctly ordered lexicographically. Numbers in the string come before letters and upper case letters come before lower case letters.

This is the ordering of the letters etc. in the Unicode Table. If you remember that all characters are represented by a number in the Unicode table this means that string comparison involves comparing one list of numbers against a second list of numbers.

Lets look at a quick example.

Now it is your turn

Can you work out what these two if statements do?

1if "robin" < "blackbird" {
2    fmt.Println("Blackbird comes before robin in the dictionary")
3}
4
5if "robin" > "blackbird" {
6    fmt.Println("Blackbird comes before robin in the dictionary")
7}

Lets look at the first if statement first

1if "robin" < "blackbird" {
2    fmt.Println("Blackbird comes before robin in the dictionary")
3}

the condition in the if statement is false so nothing is printed. So the string “robin” is not less than the string “blackbird” i.e. it is considered bigger. This is correct based on the dictionary order.

Notes

You can prove this is you look up both “robin” and “blackbird” in the dictionary. “Robin” comes after “blackbird” so “robin” must be greater than “blackbird”

The second if statement

1if "robin" > "blackbird" {
2    fmt.Println("Blackbird comes before robin in the dictionary")
3}

Is true, so the output would be

"Blackbird comes before robin in the dictionary"

String comparison really is as easy as that.

Back to if else

Now it is your turn

Lets start by looking at if statements again. Try to write some if statements that solve this.

If the population of China is greater than the population of the UK then print out There are more people in China!.

If the population of the UK is greater than the population of China then print out There are more people in the UK!.

You’ll need to create to new variables, but you won’t need to assign any value to them.

How many if tests do you need to do this?

Can all of the if statements be true at once?

You could write the if tests like this

1var populationOfChina int
2var populationOfUK int
3
4if populationOfChina > populationOfUK {
5    fmt.Println("There are more people in China!")
6}
7if popualtionOfUK > populationOfChina {
8    fmt.Println("There are more people in the UK!")
9}

But you need to use two if statements. But only one of these if statements can be true.

The if else pattern

If you have a situation where you want one action to happen when the condition is true and another action to happen when the same condition is false then you should use the if else pattern.

The pattern is an extension to the if pattern and uses the new else keyword. The pattern is

if condition {
    true-statement-block
} else {
    false-statement-block
} // this is the last brace

If the condition is true then the if else behaves like an ordinary if statement and the true-statement-block is executed. The false-statement-block is skipped over and not executed. Execution continues after the last brace.

If the condition is false then whatever follows the else is executed. In this case the false-statement-block is executed. The true-statement-block is ignored and skipped over. Once the false-statement-block has executed program execution continues after the last brace.

As you can see the if else statement executes only one of the blocks. Either the true-statement-block is executed or the false-statement-block is executed but never both blocks.

Now you know about if else statements you can write the two if statements you needed to work out which country had a bigger population using a single if else statement like this.

var populationOfChina int
var populationOfUK int

if populationOfChina > populationOfUK {
    fmt.Println("There are more people in China!")
} else {
    fmt.Println("There are more people in the UK!")
}

Important

Remember only one of the fmt.Prinln lines will be executed. The output is either

There are more people in China!

or this

There are more people in the UK!

There is one slight tweak left.

If the first statement in the false-statement-block is an if statement you are allowed to write this

if first-condition {
    true-statement-block-for-first-condition
} else if second-condition {
    true-statement-block-for-second-condition
} else {
    statement-block-if-both-conditions-are-false
} // this is the last brace

So you are allowed to squeeze the extra if statement in after the else. We will show you an example of this in program.

The times question Program

The timesquestion program tests your multiplication for the 1 to 12 times tables. If you answer correctly the program displays a congratulations message. If you are wrong the program tells you if your guess was to large or to small and then prints out the correct answer.

At the heart of the program is an if else statement.

Lets look at the timesquestion program.

 1package main
 2
 3import (
 4	"fmt"
 5
 6	"github.com/gophercoders/random"
 7	"github.com/gophercoders/simpleio"
 8)
 9
10func main() {
11
12	var a int
13	var b int
14	var answer int
15
16	fmt.Println("The timesquestion shows you how to use if and else.")
17	fmt.Println("Can you remember your times tables?")
18	fmt.Println("")
19
20	a = random.GetRandomNumberInRange(1, 12)
21	b = random.GetRandomNumberInRange(1, 12)
22
23	fmt.Print("What is ")
24	fmt.Print(a)
25	fmt.Print(" * ")
26	fmt.Print(b)
27	fmt.Println("?")
28
29	answer = simpleio.ReadNumberFromKeyboard()
30
31	if answer == a*b {
32		fmt.Println("Congratulations! You are correct! ")
33	} else if answer > a*b {
34		fmt.Println("Sorry, your guess was to big.")
35		fmt.Print("The correct answer is ")
36		fmt.Print(a)
37		fmt.Print(" * ")
38		fmt.Print(b)
39		fmt.Print(" = ")
40		fmt.Println(a * b)
41	} else {
42		fmt.Println("Sorry your guess was to small.")
43		fmt.Print("The correct answer is ")
44		fmt.Print(a)
45		fmt.Print(" * ")
46		fmt.Print(b)
47		fmt.Print(" = ")
48		fmt.Println(a * b)
49	}
50	fmt.Println("Run the program again to try another question.")
51}
Fig-1. The timesquestion code

Type the program into your text editor and try to run it. Remember that you will also need to create a new directory in your Go workspace.

If the program runs correctly the output is

The timesquestion shows you how to use if and else.
Can you remember your times tables?

What is 4 * 12?
48
Congratulations! You are correct!
Run the program again to try another question.

If the guess is to small the output is

The timesquestion shows you how to use if and else.
Can you remember your times tables?

What is 12 * 10?
5
Sorry your guess was to small.
The correct answer is 12 * 10 = 120
Run the program again to try another question.

If the guess is to large the output is

The timesquestion shows you how to use if and else.
Can you remember your times tables?

What is 3 * 8?
44
Sorry, your guess was to big.
The correct answer is 3 * 8 = 24
Run the program again to try another question.

Important

Both numbers involved in the multiplication are chosen randomly. These are the numbers we had when we ran the program. The numbers you see will be different and they will be different each time the program is run.

Lets look at the key points of the program. The first key line is line 29.

answer = simpleio.ReadNumberFromKeyboard()

This is a straight forward variable assignment statement. The value of answer is assigned the result of the function ReadNumberFromKeyboard in the simpleio package. So, the number that you type is assigned to the answer variable.

The next key lines are lines 31 to 33.

if answer == a*b {
    fmt.Println("Congratulations! You are correct! ")
} else if answer > a*b {

This is the if else pattern. Lets break this down. a and b are the numbers picked by the program. Then you are asked to solve a * b and your answer is held in answer.

If your answer is equal to a * b then the condition of the if statement is true. If the condition is true then line 32 is executed and

Congratulations! You are correct!

appears in the output. The else block that extends between lines 33 and 49 is skipped. The next line that is executed is therefore line 50, resulting in

Run the program again to try another question.

appearing in the output.

But what happens if the the answer is wrong? What happen when the condition is false?

Lets look at the whole block from lines 31 to 49.

if answer == a*b {
    fmt.Println("Congratulations! You are correct! ")
} else if answer > a*b {
    fmt.Println("Sorry, your guess was to big.")
    fmt.Print("The correct answer is ")
    fmt.Print(a)
    fmt.Print(" * ")
    fmt.Print(b)
    fmt.Print(" = ")
    fmt.Println(a * b)
} else {
    fmt.Println("Sorry your guess was to small.")
    fmt.Print("The correct answer is ")
    fmt.Print(a)
    fmt.Print(" * ")
    fmt.Print(b)
    fmt.Print(" = ")
    fmt.Println(a * b)
}

If the user types the wrong answer then the first condition

if answer == a*b {

is false. So the else on line 33 is executed.

} else if answer > a*b {

But the else block itself starts with another if statement.

If this second if test

if answer > a*b {

is true, then the users guess is too large. In this case the next block to be executed is from line 34 to 40

fmt.Println("Sorry, your guess was to big.")
fmt.Print("The correct answer is ")
fmt.Print(a)
fmt.Print(" * ")
fmt.Print(b)
fmt.Print(" = ")
fmt.Println(a * b)

which results in

Sorry, your guess was to big.
The correct answer is 3 * 8 = 24

appearing in the output. So even though the if statement follows and else it behaves in the same was as any other if statement. If this if test is true the else block in lines 42 to 49 are skipped over.

If the if test on line 33 is false

} else if answer > a*b {

then answer is less than a * b then the else block on lines 42 to 49

fmt.Println("Sorry your guess was to small.")
fmt.Print("The correct answer is ")
fmt.Print(a)
fmt.Print(" * ")
fmt.Print(b)
fmt.Print(" = ")
fmt.Println(a * b)

which results in

Sorry your guess was to small.
The correct answer is 12 * 10 = 120

appearing in the output.

Important

Remember that lines 42 to 49 are only executed if both if tests are false.

In either case the line 50 is always executed.

If you look closely at the program there are two if else blocks. The fist one extends between lines 31 and 49. The second one is enclosed within the first one, and extends between lines 33 and 49.

The else on line 33 matches the if on line 31. The else on line 41 matches the if on line 33.

The only other significant lines are lines 20 and 21.

a = random.GetRandomNumberInRange(1, 12)
b = random.GetRandomNumberInRange(1, 12)

Both of these use the new random package we have developed. The function GetRandomNumberInRange returns a random number in the range 1 to 12. 1 being the bottom of the range and 12 being the top of the range.

The random package is imported on line 6

"github.com/gophercoders/random"

The remainder of the program is a mixture of variable declarations, lines 12, 13, 14 and Print and Println statements.

Search

Featured Lesson

Numbers

What You are Going to Learn?

Computers are used to process data. All data is made up of numbers. Yes, really! Everything is just a bunch of numbers to a computer. These are the only things they understand.

We are going to explain how numbers are used in Go programs. Then we are going to show you how to do type sums in Go.