12.3.1 if statements: if then else end elif
The Xcas language has different ways of writing
if…then statements (see Section 5.1.3). The
standard version of the if…then statement consists of
the if keyword, followed by a boolean expression (see
Section 5.1) in parentheses, followed by a statement block
(see Section 12.1.7) which will be executed if the boolean
is true. You can optionally add an else keyword followed by
a statement block which will be executed if the boolean is false:
if (boolean)
true-block
⟨else false-block⟩
(where recall the blocks need to be delimited by braces or by
begin and end).
Examples
- Input:
a:=3; b:=2:; |
if (a > b) { a:= a + 5; b:= a - b;}:; |
a,b
|
Output:
since a > b will evaluate to true, and so the variable
a will be reset to 8 and b will be reset
to the value 6.
- Input:
a:=3; b:=2:;
if (a < b) { a:= a + 5; b:= a - b;} else { a:=a - 5; b:= a + b;}:;
a,b
|
Output:
since a > b will evaluate to false, and so the variable
a will be reset to -2 and b will be reset
to the value 0.
An alternate way to write an if statement is to enclose the
code block in then and end instead of braces:
if (boolean) then true-block ⟨else
false-block⟩ end
Examples
Several if statements can be nested; for example, the
statement
if (a > 1) then a:= 1; else if (a < 0) then a:= 0; else a:=
0.5; end; end
A simpler way is to replace the else if by elif and
combine the ends; the above statement can be written
if (a > 1) then a:= 1; elif (a < 0) then a:= 0; else a:= 0.5; end
In general, such a combination can be written
if (boolean 1) then |
block 1; |
elif (boolean 2) then |
block 2; |
… |
elif (boolean n) then |
block n; |
else |
last block; |
end
|
(where the last else is optional.)
For example, if you want to define a function f by
f(x) =
| ⎧
⎪
⎪
⎨
⎪
⎪
⎩ | 8 | if x > 8 |
4 | if 4 < x ≤ 8 |
2 | if 2 < x ≤ 4 |
1 | if 0 < x ≤ 2 |
0 | if x ≤ 0
|
|
|
you can enter
f(x):= { |
if (x > 8) then |
return 8; |
elif (x > 4) then |
return 4; |
elif (x > 2) then |
return 2; |
elif (x > 0) then |
return 1; |
else |
return 0; |
end; |
}
|