If Statements
An if-statement is a decision point. It's a point in a program in which the program may decide to execute certain lines of code or not execute them at all.
If-Statement Syntax
An if-statement starts with the IF
keyword followed by a boolean expression. The boolean expression is followed by the code that should execute if the boolean expression evaluates to true, and finally the if-statement is ended with the END
keyword. This is the same keyword as is used to end subroutines and loops. Here is an example if-statement that turns the turtle and moves it if the variable x
is greater than 50:
IF x > 50
RIGHT 45
FORWARD 100
END
Boolean Expressions
A boolean expression is an expression that evaluates to true or false. Every boolean expression evalutes to just one of those two values, and only those two values. There is no ambiguity: it is either true or false. The operators that can be used in a boolean expression are in the following table:
Symbol | Name | Meaning |
---|---|---|
> | Greater Than | The value before the operator is larger than the value after the operator. |
< | Less Than | The value before the operator is smaller than the value after the operator. |
= | Equal To | The value before the operator is the same as the value after the operator. |
!= | Not Equal To | The value before the operator is not the same as the value after the operator. |
<= | Less Than Or Equal To | The value before the operator is smaller than or equal to the value after the operator. |
>= | Greater Than Or Equal To | The value before the operator is larger than or equal to the value after the operator. |
Limitations
Unlike more sophisticated programming languages, if-statements in SeaTurtle can only be composed of a single boolean expression. The operators "and" and "or" do not exist in SeaTurtle. Also, there is no "else" or "else if" clause in SeaTurtle. Anything that can be done with those clauses can simply be done with multiple if-statements in SeaTurtle.
Combining If-Statements with Random Numbers
Using if-statements together with random numbers can be a powerful way to build drawings with a bit of flair. For instance, the following portion of a program will randomly draw different shapes:
SET choice RANDOM 2
IF choice = 0
CALL circle
END
IF choice = 1
CALL square
END
IF choice = 2
CALL triangle
END
The preceding code defines a variable called choice
between 0 and 2. If choice
is 0 a circle is drawn. If choice
is 1 a square is drawn. If choice
is 2 a triangle is drawn. Of course the code assumes that subroutines for drawing the various shapes were previously defined.