top of page

Programming structures: 'if ... else'

There is another programming structure very similar to the " if " but called "if ... else " the difference is that this adds a second case that is performed when the condition of " if " is not met; An example is: " If / if " pushed the button, I turn on the LEDs, " but / else " I turn off the LEDs. This structure is used as follows: first we will put a "cycle if " menu " logic "and then we click on the gear and drag the block" else "inside the" if "in the window that appears.

Then click on the gear to close the menu and add the block comparison staying follows our structure " if ... else ":

Example 1:

In the following example, when you push the button 1, the LEDs will turn blue and if the condition is not met (ie, if we did not press anything or press any button other than 1) the LEDs are off.

The pressing of button 1 "function read " return us a 1, so what is inside the block " do " turns on the LEDs in blue, by not pressing anything or any button will perform what is inside block " else " turning off the LEDs.

Logical operators

These serve to reverse a state or join two or more conditions in a single structure " if ", " for " or " while " the two logical operators are 3: not (!) Or not : it is used when we want to be take the opposite value of the state we have (! true is the same as false ). and (&&) or and : is used when we want an action to occur if all conditions are met. or (||) or or : is used when we want an action to occur when any of the conditions is met.

An example of the logical comparisons are as follows:

If we did not press any buttons  the LEDs would be red because having the operator " not " we are telling the program to take the inverse of the condition in the " if ". If you press any button between 2 " and " 4 going turn on the horn, and if press "button 1 O " 5 horn was turned off. By using the operator " and " we are telling the program that the two conditions must be fulfilled within the " if " to realize the code inside the " if ", if only one of the two conditions is met not enter the " if " . By using the operator " or " we are telling the program when any of the conditions are met in the " if " perform the code inside the " if ".

bottom of page