So far every program has run the same statements every time. Real programs make decisions: a session counts toward a goal or it does not, a value is valid or it is rejected. An if statement runs its body only when its condition is true. Go needs braces around the body but no parentheses around the condition. An else branch handles every other case. Compare numbers with <, <=, >, >=, == (equal) and != (not equal).
A comparison produces a value of type bool, which is either true or false. The condition of an if must be a bool. Unlike some languages, Go will not treat a number such as 0 or 1 as true or false, so if minutes is a compile error. You always write the comparison you mean.
Predict and run
Does exactly 20 meet the goal?
package main
import (
"fmt"
)
func main() {
minutes := 20
if minutes >= 20 {
fmt.Println("Goal met")
} else {
fmt.Println("Keep reading")
}
}Check your prediction
Goal metChange 20 to 19 and explain the difference.
Boundaries decide the answer
Most bugs in conditions sit exactly on the boundary. minutes >= 20 and minutes > 20 agree on 19 and on 21, and disagree only on 20. Whenever you write a comparison, ask what should happen at the exact cutoff value and pick the operator that says so. Then test that value on purpose, not just a value safely inside each range.
= and == look alike but do different jobs. A single = stores a value; a double == asks a question. Go does not let you use an assignment as a condition, so writing if minutes = 20 stops at compile time instead of quietly doing the wrong thing.
More than two paths: else if
Chain else if to ask another question when the first one was false. Go checks the conditions from top to bottom and runs only the first branch whose condition is true; the rest are skipped. The final else is optional and catches everything left over.
package main
import (
"fmt"
)
func main() {
minutes := 45
if minutes >= 60 {
fmt.Println("Long session")
} else if minutes >= 30 {
fmt.Println("Solid session")
} else if minutes >= 10 {
fmt.Println("Short session")
} else {
fmt.Println("Barely started")
}
}Solid sessionOrder matters. A session of 45 minutes is also at least 10, but the >= 30 test comes first and wins. If you reversed the chain and checked >= 10 first, every session of 10 minutes or more would print Short session.
Combining conditions
Sometimes one comparison is not enough. Go has three logical operators that work on bool values:
&&(and) is true only when both sides are true.||(or) is true when at least one side is true.!(not) flipstruetofalseand back.
Go evaluates && and || from left to right and stops as soon as the answer is known. You can also store a condition in a variable with a clear name, which makes a long if easier to read.
package main
import (
"fmt"
)
func main() {
minutes := 250
valid := minutes >= 1 && minutes <= 240
fmt.Println(valid)
if !valid {
fmt.Println("Use 1 to 240 minutes")
}
}false
Use 1 to 240 minutesName the rule, not the arithmetic
A variable such as valid or goalMet turns a condition into a sentence. if !valid reads almost like English, while repeating minutes >= 1 && minutes <= 240 in several places invites one copy to drift out of step with the others.
Braces and scope
The braces after if and else are required, even for a single statement, and the opening brace must sit on the same line as the condition. A variable declared inside those braces exists only there. Declare a variable before the if when you need its value afterwards, which is exactly what you will do with running totals in the next lessons.
Practice
Your turn
Label one session from its minutes. A value outside 1 to 240 prints Invalid. Otherwise, 60 or more prints Long, 20 or more prints Medium, and anything else prints Short. Write it once, then change minutes and run again for each row:
minutes | Output |
|---|---|
| 0 | Invalid |
| 19 | Short |
| 20 | Medium |
| 60 | Long |
| 241 | Invalid |
package main
import (
"fmt"
)
func main() {
minutes := 60
fmt.Println(minutes)
}Hint 1: the idea
Rule out the invalid values first with one combined condition. After that, else if branches only ever see a valid number, and the first branch that matches wins, so put the largest cutoff first.
Hint 2: a first step
Write valid := minutes >= 1 && minutes <= 240 and print Invalid when !valid. Run it with 0 and with 241 before you add the other branches.
Worked solution
package main
import (
"fmt"
)
func main() {
minutes := 60
valid := minutes >= 1 && minutes <= 240
if !valid {
fmt.Println("Invalid")
} else if minutes >= 60 {
fmt.Println("Long")
} else if minutes >= 20 {
fmt.Println("Medium")
} else {
fmt.Println("Short")
}
}LongThe rows at 19, 20 and 60 test the boundaries, where a > written in place of >= would give the wrong label. Checking >= 20 before >= 60 would label 60 as Medium, because only the first true branch runs.
Completion is saved in this browser only. It does not measure mastery.