Julia, lesson 4
A program that always does the same thing is not very useful. if lets it react to its data:
Julia blocks start with a keyword and finish with end. No braces or colons are needed, and the
indentation is only for people reading the code (but always indent; it makes the structure
obvious).
Test several conditions in order with elseif, and handle "everything else" with else. Julia
runs only the first branch whose condition is true:
| Operator | Meaning |
|---|---|
== | equal |
!= (or ≠) |
2 exercises to try what you just read.
| not equal |
<, <=, >, >= | less / greater than |
Julia lets you chain comparisons the way you would write them in maths:
Strings compare with == too, and the comparison is case-sensitive.
a && b is true when both are true.a || b is true when at least one is true.!a flips true and false.Both && and || stop early: if the left side already decides the answer, the right side is
never evaluated. Julia programmers sometimes use that as a one-line if, for example
count == 0 && println("Nothing found").
The condition of an if must be an actual Bool. Unlike some languages, Julia does not treat
0, "" or an empty list as false; writing if 1 is an error. Compare explicitly, for example
if n != 0.
Like most things in Julia, if is an expression. Its value is the value of the branch that ran.
For simple two-way choices there is a compact form, the ternary operator
condition ? value_if_true : value_if_false:
The spaces around ? and : are required. Keep ternaries short; when a choice needs more than
one line, use a normal if.
Variables assigned inside an if block remain available after it, because if does not create
a new scope.
Read a battery level from 0 to 100 and print its status:
0 to 10: Critical11 to 30: Low31 to 99: OK100: FullSample input:
Sample output:
Read three whole-number side lengths on one line, separated by spaces. (The starter already
reads them: a, b, c = ... unpacks the three parsed numbers into three variables.) Print what
kind of triangle they make:
invalid if any side is 0 or less, or if the two shorter sides together are not longer than
the longest side (in other words, if any side is greater than or equal to the sum of the other
two),equilateral if all three sides are equal,isosceles if exactly two are equal,scalene if all are different.Sample input:
Sample output:
battery = 15
if battery < 20
println("Battery low, please charge")
endif temp < 0
println("Freezing")
elseif temp < 15
println("Cool")
else
println("Warm")
endif 18 <= age < 65
println("Working age")
endlabel = n % 2 == 0 ? "even" : "odd"25Low3 4 5scalene