Previous Up Next

12.3.1  if statements: if then else end elif

The Xcas language has different ways of writing if…then statements (see Section 6.1.3). The standard version of the if…then statement consists of the if keyword, followed by a boolean expression (see Section 6.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.


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) =






   8if  x > 8
   4if  4 < x ≤ 8
   2if  2 < x ≤ 4
   1if  0 < x ≤ 2
   0if  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;
}

Previous Up Next