Booleans and Comparisons
Prerequisites: Types and conversion
Comparisons produce true or false (type Bool):
x = 7
println(x == 7, " ", x != 7, " ", x < 10, " ", x >= 8)
println(1 < x < 10)
println(0 ≤ x ≤ 5)
println(!(x > 5))
println(x > 5 && x < 10, " ", x < 5 || x == 7)
println("apple" < "banana", " ", "Zoo" < "apple")
println(1 == 1.0, " ", 1 === 1.0)
true false true false
true
false
false
true true
true true
true false
!=or≠for "not equal";≤and≥also work (type\leand\ge+ Tab).- Comparisons chain like in math:
1 < x < 10. &&(and),||(or),!(not).- Strings compare alphabetically by character code, so uppercase letters come before lowercase.
==compares values;===checks that two things are identical (same type and same bits, or the same object).
Short-circuit evaluation
&& and || stop as soon as the answer is known — which is often used
as a compact "if":
function check_age(age)
age < 0 && return "invalid"
age >= 18 || return "minor"
return "adult"
end
println(check_age(-3), " ", check_age(12), " ", check_age(30))
invalid minor adult
Read cond && action as "if cond, then action" and
cond || action as "unless cond, action".
Only Bool is a condition
Unlike Python or JavaScript, Julia doesn't treat 0, "", or an empty
list as false — conditions must be real Bool values:
items = Int[]
try
if length(items)
println("has items")
end
catch err
println(typeof(err))
end
println(isempty(items))
TypeError
true
Write the test you mean: isempty(items), length(items) > 0,
x != 0. (try/catch catches the error here so the program can keep
going; Level 2 covers it.)