next up previous contents index
Next: ternary conditional Up: Control Structures Previous: return   Contents   Index

if, elif, else

if expression1
statements1
elif expression2
statements2
...
elif expressionN
statementsN
else
statements
end

If expression1 evaluates nonzero, statements1 will be executed, otherwise if expression2 evaluates nonzero, statements2 will be executed, and so on. If none of the expressions evaluate nonzero, statements following else will be executed. The only parts that are mandatory are if, expression1, and end, all other clauses are optional.

Note that elif is not the same as ``else if''. The following two blocks are equivalent:

# example using "elif"
if (a == 1)
    Print(1)
elif (a == 2)
    Print(2)
else
    Print("?");
end

# example using "else if"
if (a == 1)
    Print(1)
else
    if (a == 2)
        Print(2)
    else
        Print("?")
    end
end

In particular, a common error is the following:

if (a == 1)
    Print(1)
else if (a == 2)
    Print(2)
else
    Print("?")
end

This is missing an ``end'' statement (see the second form above).



Stephen R. Whiteley 2024-09-29