Conditional Statements Hi, this is Nick Bennett. In this video we're going to look at conditional statements and see simple examples of their use in NetLogo. [Slide 1] In computer science, the term "control flow," sometimes "control of flow, flow of control," or "flow control," refers to the order in which statements are executed and expressions evaluated. While a linear sequence of operations is sufficient for many basic calculations, more complicated computations, unpredictable inputs, or more general purpose programs usually require a non-linear sequence of operations. For example, it might be necessary to repeat some operations multiple times or bypass some operations under some conditions. In this video we'll explore one class of flow control constructs. Conditional statements and expressions. [Slide 2] Fundamentally, conditional statements are used to specify that a sequence of operations should be performed if a given logical condition is true and skipped otherwise. Some non-programming examples of this would be if the low fuel indicator light is on when you start the car, drive directly to the gas station and fill the tank. Or if you hear the tornado siren, seek shelter immediately. In both cases there are instructions to follow if some condition holds true. Also, both examples use the word "if". In English, "if" is a conjunction that most often serves to introduce a conditional clause. It serves the same purpose in most programming languages. [Slide 3] In programming the generic name for a simple conditional statement is the "if, then" statement. Without focusing on any single programming language, the general structure of the "if, then" statement is shown here. Condition is a boolean expression. In other words, one which is either true or false. [Slide 4] In the examples just given, the conditions were the low fuel indicator light is on when you start the car and you hear the tornado siren. Each of these is either true or false at the relevant moments in time. The statements following "then" are the operations to be performed if the condition is true. Note that neither example actually includes the word "then", but both of them have an implicit "then". In the examples, what are the operations to perform if the conditions are true? [Slide 5] You probably had no trouble identifying, drive directly to the gas station and fill the tank and seek shelter immediately, as the operations to perform conditionally in the examples. conditional-statements-smaller Page 1 of 7 Of course, there may very well be other conditions under which we would perform those operations. For example, we might fill the gas tank before a long drive, even if the fuel light isn't on immediately before we fill the tank. In programming, this would be expressed by multiple conditional statements. Each with different conditions but with some operations in common. [Slide 6] Now, let's look at language specific syntax. In NetLogo as well as most other dialects of Logo, the "if, then" statement Is expressed as it appears here. The required elements are the "if" keyword, the white space between "if" and the condition, the condition itself, and the square brackets. Another thing to note is that the use of the term "commands" inside the brackets is deliberate. In NetLogo, when we have a pair of brackets enclosing a sequence of statements, we call it a command block. The indentation in the NetLogo conditional statement is up to the programmer. So are the positions of the square brackets. Some programmers place the opening bracket on the same line as the condition. Some even put the commands and the closing bracket on that same line, especially if only a single command is to be executed conditionally. The condition could be as simple or as complicated as necessary. However, it must be a boolean expression. In other words, it must evaluate to true or false. [Slide 7] Let's look at an example in an actual model. I have a simple model that creates fifty turtles and then moves them around the NetLogo world in wiggle motion. There's a twist. In the model settings dialogue, [Slide 8] I've turned "world wraps horizontally" and "world wraps vertically" off. This means that the world is no longer a taurus [?]. Instead, it's a box. Notice the red lines around the small view of the NetLogo world. These indicate that the edges of the world or impassable walls. For example, turtles can no longer move off the right hand side of the world and automatically appear on the left hand side. What do you think happens when a turtle is at the edge of the world configured this way and it tries to take a step that would go past the walls? [Slide 9] When I run this model, we quickly see that turtles seem to get stuck for a time on the edges, where there are now walls. NetLogo is stopping them there, preventing them from moving through the walls. Of course, eventually, they turn enough in their wiggling that they're no conditional-statements-smaller Page 2 of 7 longer facing a direction that leads through a wall with a single step. They can once again move forward. I don't want them to get stuck at all. [Slide 10] Instead, I'd like them to bounce off the walls. For now, this doesn't need to be a reflection, where the angle of reflection is equal to the angle of incidence. Instead, it's just going to be a simple one hundred eighty degree turn to reverse their direction. To do this I'll use a conditional statement. [Slide 11] Here in the model code we have the "wiggle" procedure, which is called by the "go" procedure. As you can see, the maximum turn angle is only ten degrees. This is a pretty narrow wiggle. In the change I want to make, I still want my turtles to turn randomly. Then, before they move forward, I want them to see if, in fact, they can't take the full step because of the walls. I'll add the conditional just before the "forward" command. As it turns out, NetLogo gives us a very easy way to tell if a turtle can move a specified distance forward. The built-in reporter procedure called, "can move." When a turtle invokes this procedure with the number for the distance it wants to move, the value true or false is returned. True if the turtle can take a step of the specified step in the direction it's facing. False if taking that step would require going through a wall at the edge of the world, in which case NetLogo would stop the turtle at the wall. I want to have the turtle reverse directions in the event that "can move" returns a value of "false." In the "if, then" statement, the commands are executed only if the condition is "true." I need to flip the value returned by "can move," making a false value true and vice versa. I do this with the logical "not" operator. My conditional statement begins with, "if not, can move one." One is the distance that the turtle will move if it can. It matches the distance specified in the forward command. Notice that the question mark is part of the name of the "can move" reporter procedure. We have to include it in our code. Inside the brackets I need to put the command or commands to be executed if the condition is true. In this case, I want the turtle to turn one hundred eighty degrees. Doesn't matter whether it's to the left or the right. Turning one hundred eighty degrees in either direction results in the same heading for the turtle. I'll use left this time. After I close my brackets and assuming I made the change with correct syntax, I'm ready to see the result. [Slide 12] When I click the "set up" button and then the "go" button, it's clear that the conditional-statements-smaller Page 3 of 7 change has the desired effect. The turtles now bounce off the walls rather than being stuck. [Slide 13] It's often the case that we want one sequence of operations to be performed under some condition, but if that condition doesn't hold, we want a different sequence of operations to be performed. In other words, instead of imply performing some sequence or not based on a condition, we want to choose between two sequences. We choose the first sequence if the condition is true and the second if the condition is false. [Slide 14] In programming, we call this an "if, else" statement. The general form is shown here. One important point to note, is that anything we can do with an "if, else" statement, we can also do with multiple "if, then" statements. The "if, else" simply makes it easier to express an exclusive choice between two sequences of operations. [Slide 15] NetLogo, in fact Logo in general, has one of the more quirky syntax forms for this statement. In NetLogo, we write the "if, else" statement as shown here. Note that there are now two command blocks. Both sets of brackets are required. Also, "if, else" is written as a single word without a space, dash, or any other separator between "if" and "else." Be careful when typing an "if, else" in NetLogo. One common mistake is forgetting to include the second command block. Another is forgetting to close the first set of brackets before opening the second. [Slide 16] Let's go back to my example model and see how we might use an "if, else" there. Remember that when a turtle is unable to move a full step in the direction it's facing, it reverses direction before taking a step forward. There are at least two potential problems with this. For one thing, it's possible to get stuck in a corner of the NetLogo world in such a way that a turn of one hundred eighty degrees doesn't leave the turtle facing a direction where it can take a full step. It will simply end up hitting a wall in the new direction. Another potential issue is that in the real world turning takes time. Just as moving forward or back does. The turtles in the model have already turned randomly to the right and left before checking to see if they are unable to take a full step forward. Some of them will take an additional turn of one hundred eighty degrees and then take a step forward. It's implicitly assumed that doing that takes the same amount of time as taking the step forward without first reversing direction. That might not be a reasonable assumption. conditional-statements-smaller Page 4 of 7 [Slide 17] I'm going to modify the movement logic in the model so that a turtle with either reverse direction or take a step forward but not both in a single execution of the "wiggle" procedure. Note that this fits exactly with our understanding of the "if, else" statement. The turtle would choose between two different sequences of operations based on a single condition. To make the model more visual, I'm also going to use color to indicate whether a turtle is stuck against the wall, if even for a single iteration. If a turtle can't take a full step forward, I'll set its color to red. Otherwise I'll set its color to green. [Slide 18] First, I set the initial turtle color to green by adding "set color green" to the command block that follows create turtles in the "set up" procedure. Next, I change the "if" in the "wiggle" procedure to "if, else." I'll leave the condition exactly as it is, but before the left one eighty in the command block, I need to add "set color red" to indicate visually that the turtle is at least momentarily stuck. It can't take a full step forward in the direction it's facing and must, instead, reverse direction. Now I add a second command block, containing the commands the turtle will execute if the condition is false. That is, if the turtle actually can take a full step in the direction it's facing. The first command in this command block will be "set color green" to indicate that the turtle is able to move freely as desired at that moment. Next, I'll move the forward one that was at the bottom of the procedure into this command block. So that only a turtle that can move forward will do so. That's all I need in the second command block so I can now close the brackets. [Slide 19] After making the change, I need to click "set up" so that all the turtles start out green. When I run the model, it looks much the same as it did after the first change. We can occasionally see turtles at the edges of the world briefly changing color to red. In fact, there are enough turtles and the world is small enough that if I stop the model running at any point, there are usually a few red turtles around the edges. We've now seen the two basic conditional statements in NetLogo. There is also another construct we should look at, the conditional expression. Instead of choosing between two sequences of operations to perform, based on a single condition, a conditional expression evaluates to one of two possible values based on a single condition. Once again, in any programming language that has conditional statements, anything we can do with a conditional expression can also be done with conditional statements. Conditional expressions can make conditional-statements-smaller Page 5 of 7 some things simpler. There is not a widely used generic form of the conditional expression. The form used in the C programming language is also used in many related languages but it can appear a bit cryptic at first. Let's go straight to the NetLogo syntax, where the conditional expression takes this form. As before, condition is a boolean expression and the square brackets are required. In this case, however, they don't delimit command blocks. Instead, they enclose expression. Both of which are required and one of which will be evaluated based on whether condition is true or false. If its value is true, then the value of the entire "if, else" expression is expression one. Otherwise, the entire expression has the value expression two. The conditional expression can be a bit tricky to understand clearly without a concrete example. Let's go back to the model. This time, I'm going to change the color assignments for the turtles that are able to move. Those that are moving to the left will be colored blue while those moving to the right will be colored green. For this, I need to edit the "wiggle" procedure again. The second command block of the "if, else" conditional statement is where a color is assigned to a turtle just before it moves forward. To that command, I need to add a check of the heading. If the turtle's heading is greater than or equal to one eighty, that is, if it's headed in a general right to left direction, it will be colored blue. Otherwise, it will be colored green. Of course, I could do this with an "if, else" conditional statement, but it will be much simpler with "if, else" value. I change the "set color green" command, replacing green with an "if, else" value expression where the condition is "heading greater than or equal to one eighty," and the expression to evaluate if the condition is true, is the color constant "blue" in the first set of brackets. The expression to evaluate if the condition is false, is the color constant "green" in the second set of brackets. Note that the parentheses, the set enclosing in the entire expression being assigned to color as well as the set enclosing the condition "heading greater than or equal to one eighty," are optional. I find that they make complicated lines of code a little easier to read and understand, but that's simply my preference. In any event, we can understand this line to mean that if the turtle's heading is greater than or equal to one eighty color it blue. conditional-statements-smaller Page 6 of 7 Otherwise, color it green. When we run the model with this change, we see red, green, and blue turtles as expected. The red turtles are close to the edges, the blue turtles are moving right to left, and the green turtles are moving left to right. I hope this introduction to conditional statements and expressions and their use in NetLogo will help you continue to improve your NetLogo programming capabilities. Please remember that these constructs are documented in the NetLogo dictionary, and that examples of their use can be found in almost all of the models in the NetLogo models library. conditional-statements-smaller Page 7 of 7