Bitpath

Lesson 1 · Unit 02

Conditions

Comparisons, if and else, and, or and not, and switch.

13 exercisesabout 3 min

What you practise

  • Comparisons, &&, ||, !, if, else if, else, switch without fall-through, the short statement before a condition

Try a question from this lesson

Pick one

The lines inside the braces run only if the question after if is true. What does this print?

Go
age := 15
if age >= 18 {
  fmt.Println("adult")
}
fmt.Println("done")

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

if and comparisons

An if asks a yes-or-no question. If the answer is true, the lines between its braces run. If it is false, Go skips them.

The questions are comparisons, and each one gives a bool: == equal, != not equal, < less than, > greater than, <= at most, >= at least.

Note the double sign: == compares, while a single = stores a value.

Go
temp := 25
if temp > 20 {
  fmt.Println("warm") // runs
}
fmt.Println(temp == 30) // false

Concept

else and else if

An if can have an else: lines to run when the answer is false.

With else if you can ask a second question, and a third. Go asks them from the top, runs the first branch whose answer is true, and skips all the rest, even if a later question would also be true.

Go
temp := 12
if temp > 25 {
  fmt.Println("hot")
} else if temp > 15 {
  fmt.Println("mild")
} else {
  fmt.Println("cold") // runs
}

Concept

switch

When one value is compared against a list of possibilities, switch reads better than a long chain of else if.

Go checks the cases from the top and runs the first one that matches. Only that one: when its lines are done, Go leaves the switch. default runs when nothing matched.

Go
coins := 2
switch coins {
case 1:
  fmt.Println("one coin")
case 2:
  fmt.Println("two coins") // runs
default:
  fmt.Println("many coins")
}

9 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 3× multiple choice
  • 1× match the pairs
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy