While And Until
While
The
whilestatement repeats a block of code while a condition is true.
Example
while boolean (
command
command
)Syntax
while condition (
commands
)condition: The condition that determines whether to continue executing the block of commands.commands: The commands to be executed within the loop.
Example
while distance_to_object < 10 (
robot "moveForward" 10
robot "turnLeft" 10
robot "get_data"
distance_to_object = robot."sensor1"
)In this example, the robot will keep moving forward and turning left as long as there is an obstacle ahead.
Until
The
untilstatement repeats a block of code until a condition is true.
Example
Syntax
condition: The condition that determines whether to stop executing the block of commands.commands: The commands to be executed within the loop.
Example
In this example, the robot will keep moving forward until the goal is reached.
Use Cases
User Input Validation with
while
This example demonstrates how the while statement can be used to repeatedly prompt the user for input until a valid value is entered.
Waiting for External Event with
until
Here, the until statement is used to wait until a sensor detects an object before proceeding with the next set of commands.
Last updated
Was this helpful?