A conditional statement because it gives a program a choice. A conditional statement has three parts. The first part is an expression that is either true or false. The second part specifies what to do if the expression is true. The third part, which is optional, specifies what to do if the expression is false.
A conditional statement is very handy in many situations. For example, we may want to draw a hexagon with different colors. Let us start with an alternative program to our old drawpolygon.
This is essentially the same as our old program. However, the for construct needs two components.
The first component specifies three things. It specifies a variable, and a range of values that it will assume in consecutive iterations. In our example for se se "i 1 :n means variable i will assume a value from 1 to the value of variable n. This means that if variable n has a value of 6, then variable i assumes the values from 1 to 6.
The second component specifies that for each value of varaible i, what should be done. For a simple test, input the following line in the command line of XLogo:
Note the use of se (sentence). This command takes two additional items, and form a list. This means that se 1 2 is the same as [1 2] (the square brackets enclose a list). However, se i 1 is incorrect, as i is interpreted as a comment. As a result, se i 1 does not work unless you have a command called i.
se can also be used to merge a list with an item. This is why se se "i 1 :n works. Let us assume variable n has a value of 6. The “inner” se "i 1 creates a list of [i 1]. The outer se se "i 1 :n merges the list [i 1] with the value of variable n, which is 6. As a result, the entire expression produces a list of [i 1 6].
So, why didn’t [i 1 :n] work? The “value-of” (colon) operator does not work in square brackets. Everything in square brackets are “literal” and receives no special treatment (to execute commands or find the value of variables).
For a simpler case, let us use the following as an example to illustrate the basic concept of the for command:
Note the use of :i to refer to the value of i.
Knowing that the value of i changes for each edge of a polygon, we can now use it to change the color as follows:
Let us examine this code a little more closely. mod :i 2 computes the remainder of the value of variable i divided by 2, and this whole expression becomes a number. equal? mod :i 2 0 is checking whether the remainder of the value of i divided by 2 equals to 0, and answers with either a value of true or a value of false. If the answer is true, then setpc [0 255 0] sets a pen color of green. Otherwise, setpc [255 0 0] set a pen color of red.