Coding 9: The If Statement


#1

Coding Threads

Coding 0: Welcome To Coding Camp. Installing Computercraftedu and using the Turtle Remote
Coding 1: Enter The Turtle Garden. Learning how to control your Turtle.
Coding 2: The Enchanted Forest. Practicing Turtle movement.
Coding 3: Building And Repeats. Learning to build with your Turtle.
Coding 4: The Enchanted Meadow. Practicing Building and Repeats.
Coding 5: Nested Repeats. Learning to stack repeats.
Coding 6: Turtle Town. Practicing repeats.
Coding 7: The Big Dig. Learning to dig and practicing loops.
Coding 8: Million Mile Mines. Practicing digging and loops.
Coding 9: The If Statement. Learning about conditional statements.
Coding 10: The Working Turtle. Writing complex programs with conditions and loops.

##The IF Statement

IF statements allow the Turtle to run different commands under different conditions. You may have noticed your Turtle becomes unhappy when they try to move but there is a block in the way. Using an IF STATEMENT your Turtle can be told to move only if there is room for them.

<img src=http://drive.google.com/uc?export=view&id=0Byh5jOX2Lh-FS1ZpUDJQNUl0N0E>

The IF Statement starts with the IF block and then a conditional statement. In the example above the first statement (DETECT = FALSE) checks if there is a block in front of the Turtle. If there is not a block in front of the Turtle than all of the code in between THEN and END will run.

<img src=http://drive.google.com/uc?export=view&id=0Byh5jOX2Lh-Fa0RlZktSb2VqOXM>

One of the most useful blocks to use with the IF statement is DETECT. By testing whether there is block in front of, above, or below the Turtle you can code your Turtle to respond to the world around it.

<img src=http://drive.google.com/uc?export=view&id=0Byh5jOX2Lh-FcHh1X0N3bzZ5bjQ>

When asking your Turtle to DETECT the Turtle will either respond with TRUE or FALSE. If DETECT is TRUE the Turtle found a block in front of them. Only then will your IF code run. Otherwise the Turtle will skip over the code like it isn’t even there.

In the code below an ELSE block has been added. The code between ELSE and END will only run if the code between THEN and ELSE does not. In the example below the Turtle will move forward if it does not detect a block in front. Otherwise the Turtle will turn to the right.

<img src=http://drive.google.com/uc?export=view&id=0Byh5jOX2Lh-FT1QxOVN0dVVvZDA>

Turtles can also use ELSE IF blocks. These work like ELSE blocks but also have a condition attached to them. You can stack as many ELSE IF blocks together as you want!

<img src=http://drive.google.com/uc?export=view&id=0Byh5jOX2Lh-FVF9iV1NMajE2VGs>


Coding 0: Welcome To Coding Camp
Coding 8: Million Mile Mines
Coding 6: Turtle Town
Coding 7: The Big Dig
Coding 3: Building And Repeats
Coding 5: Nested Repeats
Coding 1: Enter The Turtle Garden
Coding 2: The Enchanted Forest
Coding 4: The Enchanted Meadow

Back to Connected Camps Homepage