ifelse

 

ifelse is used to define two sets of rules to be followed by turtles conditionally: one set if a provided condition is true and another set if the condition is false. To do so, we use the following format: ifelse condition(s)[...][...].

ask cows [
    ifelse thirst > 10 [
        drink-water
    ][
        eat-grass
    ]
]

Things to keep in mind when using if-else:

The model example has some cars driving down a road and a gas station in the middle. The cars stop at the gas station to top up their tanks before moving on. At each tick, each car checks if it is at the gas station and if its tank is not full (less than 1) (if the patch they are on has an x coordinate of 0). If it is not at the gas station, it keeps moving. If it is at the gas station,it starts filling up its tank until full. Otherwise, it starts moving again. Each time a car drives, it loses a little bit of gas, so when it loops back around to the gas station again, it will refill its tank.

 

Try it Yourself

 
 
 
 
 
 
 

What's next?

Once you mastered the ifelse primitive, don't stop there. Check out the resources below to improve your NetLogo skills.

 
Published NetLogo models that use the ifelse primitive:
 
 
Similar primitives:
if

Carries out a provided set of rules (code) if a given condition is true. Does nothing if a given condition is false.

Read more
ifelse-value

Picks a value based on a provided list of condition-value pairs.

Read more
or

Checks if either of two provided conditions is true.

Read more
and

Checks if both provided conditions are true.

Read more
 
Learn another primitive: