11-if/questions/2-logical-operators.md
||!= CORRECT!&&2: That's the "not equal" operator. It's a comparison operator, not a logical operator.
3: That's right. All the logical operators return an untyped bool value (true or false).
3: That's right. All the logical operators expect a bool value (or a bool expression that yields a bool value).
"age is equal or above 15 and hair color is yellow"
age > 15 || hairColor == "yellow"age < 15 || hairColor != "yellow"age >= 15 && hairColor == "yellow" CORRECTage > 15 && hairColor == "yellow"package main
import "fmt"
func main() {
var (
on = true
off = !on
)
fmt.Println(!on && !off)
fmt.Println(!on || !off)
}
3:
!onis false.!offis true. So,!on && !offis false. And,!on || !offis true.
package main
import "fmt"
func main() {
on := 1
fmt.Println(on == true)
}
3:
onis int, whiletrueis a bool. So, there's a type mismatch error here. Go is not like other C based languages where1equals totrue.
// Note: "a" comes before "b"
a := "a" > "b"
b := "b" <= "c"
fmt.Println(a || b)
1-2: Logical operators return a bool value only.
3: Order is like so: "a", "b", "c". So,
"a" > "b"is false."b" <= "c"is true. So,a || bis true.
5: There isn't an error. Strings are actually numbers, so, they're ordered and can be compared using the ordering operators.
// Let's say that there are two functions like this:
//
// isOn() which returns true and prints "on ".
// isOff() which returns false and prints "off ".
//
// Remember: Logical operators short-circuit.
package main
import "fmt"
func main() {
_ = isOff() && isOn()
_ = isOn() || isOff()
}
// Don't mind about these functions.
// Just focus on the problem.
// They are here just for you to understand what's going on better.
func isOn() bool {
fmt.Print("on ")
return true
}
func isOff() bool {
fmt.Print("off ")
return false
}
1, 3: Remember: Logical operators short-circuit.
2: That's right.
In:
isOff() && isOn(),isOff()returns false, so, logical AND operator short-circuits and doesn't callisOn(); so it prints:"off ".Then, in:
isOn() || isOff(),isOn()returns true, so, logical OR operator short circuits and doesn't callisOff(); so it prints"on ".
4: Think again.
Example program is here.