The execution controllers enable you — as their name implies — to control execution.
Execution controlling commands are highlighted with dark green in a bold font type. The brackets are mostly used together with execution controllers and they are highlighted with black.
If you have done some programming in KTurtle you have might noticed that the turtle can be very quick at drawing. This command makes the turtle wait for a given amount of time.
- if
if boolean { ... }
The code that is placed between the brackets will only be executed
ifthe boolean value evaluates “true”.$x = 6 if $x > 5 { print "$x is greater than five!" }On the first line
$xis set to 6. On the second line a comparing operator is used to evaluate$x > 5. Since this evaluates “true”, 6 is larger than 5, the execution controllerifwill allow the code between the brackets to be executed.
- else
if boolean { ... } else { ... }
elsecan be used in addition to the execution controllerif. The code between the brackets afterelseis only executed if the boolean evaluates “false”.reset $x = 4 if $x > 5 { print "$x is greater than five!" } else { print "$x is smaller than six!" }The comparing operator evaluates the expression
$x > 5. Since 4 is not greater than 5 the expression evaluates “false”. This means the code between the brackets afterelsegets executed.
- while
while boolean { ... }
The execution controller
whileis a lot likeif. The difference is thatwhilekeeps repeating (looping) the code between the brackets until the boolean evaluates “false”.$x = 1 while $x < 5 { forward 10 wait 1 $x = $x + 1 }On the first line
$xis set to 1. On the second line$x < 5is evaluated. Since the answer to this question is “true” the execution controllerwhilestarts executing the code between the brackets until the$x < 5evaluates “false”. In this case the code between the brackets will be executed 4 times, because every time the fifth line is executed$xincreases by 1.
- for
for variable = number to number { ... }
The
forloop is a “counting loop”, i.e. it keeps count for you. The first number sets the variable to the value in the first loop. Every loop the number is increased until the second number is reached.for $x = 1 to 10 { print $x * 7 forward 15 }Every time the code between the brackets is executed the
$xis increased by 1, until$xreaches the value of 10. The code between the brackets prints the$xmultiplied by 7. After this program finishes its execution you will see the times table of 7 on the canvas.The default step size of a loop is 1, you can use an other value with
for variable = number to number step number { ... }
- assert
assert boolean
Can be used to reason about program or input correctness.
$in = ask "What is your year of birth?" # the year must be positive assert $in > 0