Kodewick
Start learning →
Lesson 3 of 24Contents

if and switch

Lesson 3 of 24 · Part 1 · Getting started · about 15 minutes

So far every line of a program runs. But often it should depend: show "Pass" only if the score is high enough, take an umbrella only if it rains. That's what if is for:

prog.go
1package main2 3import "fmt"4 5func main() {6	score := 727	if score >= 60 {8		fmt.Println("Pass")9	}10	fmt.Println("Score:", score)11}
Output
Pass
Score: 72

score >= 60 is a condition: it comes out true or false. If it's true, the block in the curly braces runs; if it's false, the block is skipped. Change 72 to 55 and run it again.

The comparison operators:

WriteMeans
a == bequal (two equals signs)
a != bnot equal
a < b, a <= bless than, less than or equal
a > b, a >= bgreater than, greater than or equal

else and else if

else means "otherwise". You can put several else ifs in between. Go checks the conditions from top to bottom and runs the block of the first one that is true; it doesn't look at the rest:

prog.go
1package main2 3import "fmt"4 5func main() {6	temp := 187	if temp >= 26 {8		fmt.Println("Hot: turn on the AC")9	} else if temp >= 16 {10		fmt.Println("Just right")11	} else {12		fmt.Println("Cold: wear a coat")13	}14}
Output
Just right

Press Step to see which conditions it checks. Note that } else { goes on one line: put else on the line after the }, and Go adds a semicolon after the }, so the program doesn't compile.

Guess first

What does this show?

1package main2 3import "fmt"4 5func main() {6	score := 957	if score >= 60 {8		fmt.Println("Pass")9	} else if score >= 90 {10		fmt.Println("Excellent")11	}12}

No parentheses, but braces

The condition needs no parentheses: write if score >= 60, not if (score >= 60) (that runs too, but gofmt removes them). The curly braces, though, are required, even around a single line:

prog.go
1package main2 3import "fmt"4 5func main() {6	price := 1207	if price > 1008		fmt.Println("Over 100")9}
Output
# command-line-arguments
./prog.go:8:26: syntax error: unexpected newline, expected { after if clause

The error points at the end of line 8: the compiler read all the way there without finding the { that must follow an if. Add { after the condition and } on a line after the fmt.Println, and it works.

And, or, not

You can combine conditions: && is "and", true only when both sides are; || is "or", true when either side is; ! is "not", which flips true and false.

prog.go
1package main2 3import "fmt"4 5func main() {6	temp := 227	raining := false8	if temp >= 18 && !raining {9		fmt.Println("Go to the park")10	}11	if temp < 5 || raining {12		fmt.Println("Stay at home")13	}14}
Output
Go to the park

raining is a bool, so it can be the condition by itself; no need for raining == true. Change raining to true and try again.

if with a short statement

An if can start with a short statement, then a semicolon, then the condition. A variable declared there exists only inside that if and its else:

prog.go
1package main2 3import "fmt"4 5func main() {6	price, count := 35, 37	if total := price * count; total >= 100 {8		fmt.Println("Total:", total, "free shipping")9	} else {10		fmt.Println("Total:", total, "shipping $10")11	}12}
Output
Total: 105 free shipping

After the if, total is gone. Add fmt.Println(total) at the end and the compiler says undefined: total. That keeps short-lived variables from piling up.

switch

When one value is compared with many, switch reads better than a long run of else if. A case can list several values with commas; if none matches, default runs:

prog.go
1package main2 3import "fmt"4 5func main() {6	day := 67	switch day {8	case 1, 2, 3, 4, 5:9		fmt.Println("Weekday")10	case 6, 7:11		fmt.Println("Weekend")12	default:13		fmt.Println("No such day")14	}15}
Output
Weekend

Unlike C or Java, a Go case leaves the switch when it's done; you don't write break.

Guess first

How many lines does this show?

1package main2 3import "fmt"4 5func main() {6	size := "M"7	switch size {8	case "S":9		fmt.Println("Small")10	case "M":11		fmt.Println("Medium")12	case "L":13		fmt.Println("Large")14	}15}

switch with no condition

Write nothing after switch, and each case is a condition. Like if, it runs the first one that is true, from the top:

prog.go
1package main2 3import "fmt"4 5func main() {6	score := 857	switch {8	case score >= 90:9		fmt.Println("A")10	case score >= 80:11		fmt.Println("B")12	case score >= 60:13		fmt.Println("C")14	default:15		fmt.Println("D")16	}17}
Output
B

It's another way to write a long if/else if chain, and it reads like a table. If you really want to go on into the next case, end the case with fallthrough, but you'll rarely need it.

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it.

Exercise 1

Pass or retake

For each of two scores, show score pass for 60 or more and score retake for less than 60. It should show 72 pass and 55 retake.

It should print
72 pass
55 retake
exercise1.go
1package main2 3import "fmt"4 5func main() {6	score := 727	fmt.Println(score)8	score = 559	fmt.Println(score)10}
Output
Press Run or Ctrl+Enter
Exercise 2

Fix it: else on its own line

This program doesn't compile. Fix it so it shows Turn on the AC and Open a window.

It should print
Turn on the AC
Open a window
exercise2.go
1package main2 3import "fmt"4 5func main() {6	temp := 287	if temp > 25 {8		fmt.Println("Turn on the AC")9	}10	else {11		fmt.Println("Open a window")12	}13	temp = 1814	if temp > 25 {15		fmt.Println("Turn on the AC")16	}17	else {18		fmt.Println("Open a window")19	}20}
Output
Press Run or Ctrl+Enter
Exercise 3

Shipping by weight

Shipping costs $8 up to 1 kg, $15 up to 5 kg, and $30 for anything heavier. Use a switch with no condition to set fee, and show 3 kg costs 15 and 12 kg costs 30.

It should print
3 kg costs 15
12 kg costs 30
exercise3.go
1package main2 3import "fmt"4 5func main() {6	weight := 37	fee := 08	fmt.Println(weight, "kg costs", fee)9	weight = 1210	fmt.Println(weight, "kg costs", fee)11}
Output
Press Run or Ctrl+Enter

What you learned

  • if condition { … } runs the block only when the condition is true; else if and else follow, and only the first true block runs.
  • No parentheses around the condition, braces always, and } else { on one line.
  • && is and, || is or, ! is not.
  • A variable declared in if x := …; condition { … } exists only in that if and its else.
  • A switch case leaves when it's done, no break needed; a case can list several values, and default runs when none match.
  • A switch with no condition makes each case a condition, replacing a long if chain; fallthrough carries on into the next case.
Finished this lesson?Mark it. Progress is saved in this browser, and you can undo it.