0.1 + 0.2 == 0.3
false
Marie-Hélène Burle
Control flow statements alter the linear execution of code, allowing for one or another section of code to be executed, or for one section of code to be executed multiple times.
Conditional statements allow to run instructions based on predicates: different sets of instructions will be executed depending on whether the predicates return true
or false
.
Here are a few examples of predicates with classic operators:
In addition, Julia possesses more exotic operators that can be used in predicates:
The function isapprox
or the equivalent binary operator ≈
(typed with \approx<tab>
) can be used:
The negatives are the function !isapprox
and ≉
(typed with \napprox<tab>
).
if <predicate>
<some action>
end
<predicate>
evaluates to true
, the body of the if statement gets evaluated (<some action>
is run),<predicate>
evaluates to false
, nothing happens.Example:
testsign1 (generic function with 1 method)
Nothing gets returned since the predicate returned false
.
if <predicate>
<some action>
else
<some other action>
end
<predicate>
evaluates to true
, <some action>
is done,<predicate>
evaluates to false
, <some other action>
is done.Example:
testsign2 (generic function with 1 method)
If else statements can be written in a terse format using the ternary operator:
<predicate> ? <some action> : <some other action>
Here is our function testsign2
written in terse format:
function testsign2(x)
x >= 0 ? println("x is positive") : println("x is negative")
end
testsign2(-2)
x is negative
Here is another example:
And in terse format:
if <predicate1>
<some action>
elseif <predicate2>
<some other action>
else
<yet some other action>
end
Example:
For loops run a set of instructions for each element of an iterable:
for <iterable>
<some action>
end
Examples:
Hello Paul
Hello Lucie
Hello Sophie
While loops run as long as a condition remains true:
while <predicate>
<some action>
end
Example: