1. The Logic of the if-elseif-else Statement The if-elseif-else statement is used when there are multiple conditions to check and only one of them can be true. The basic logic is: if condition1 is true Note: The else branch is optional.
2. Using the if-elseif-else Block We create an if-elseif-else block in a similar way as the if-else block. Click the gear icon on the if block and then drag the "else if" block under the "if" block and click them together:
We can also drag multiple "else if" blocks during the dragging process and, if we want, drag over an "else" block at the end. A typical end result would look like this:
3. Always Test All Possible Answers for if-elseif Statements When you are using an if-elseif statement (or really, any kind of if statement), it's good to run the code with all possible variations of the condition that is being checked. You want to make sure it runs correctly in all cases. Note that
|
if-elseif-else statement, if-elseif-else block
|
If a random integer between 1 and 100 is less than 30, drive the robot forward 6 inches. If the integer is greater than 70, drive the robot backward 6 inches. Otherwise, turn the robot left and drive forward 6 inches. |
The code uses a loop to continually increase the size of the robot model (a white cat), moving it slightly forward each time around the loop. Inside the loop it uses an if-elseif statement to check the position of the cat. When it reaches a position of 6, it changes the robot model to a brown cat. When it reaches a position of 12, it changes the robot model to a dog. |
The code prompts the user to click in the sky, trees, or water to move either the helicopter, bird, or boat. When the user clicks, the code stores the (x,y) coordinates of the click location, draws a dot there, and then uses a conditional "if-else if" code block to check the y coordinate of the click to determine where the user clicked and move the appropriate robot to that point. (See the lesson on Prompt the User to Click in a Rectangle for more info.) |
Grid Size: S M L | Simple View: | MinView: |
Coord: x-axis y-axis | Grid Lines: x-axis y-axis | |||
Grid: | 12x12 inches | 24x24 inches | 36x36 inches | |
72x72 inches | 96x96 inches | 192x192 inches | ||
1x1 inches | 2x2 inches | Fraction: | ||
xy-Range: | ||||
|
||||
|
||||
Quad: | 1 Quadrant | 4 Quadrants | 1&4 Quadrants | |
Units: | US Customary | Metric | Ruler: |
Labels: |
|
|
|
Font
px
|
|
Tics Lines: |
|
Width
px
|
Hash Lines: |
|
Width
px
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
(
,
in
) in
|
|
![]() |
|
|
|||||||||||
|
|||||||||||