If, then, and else

We use if statements as a logical (true or false) check. It works something like this:

        if ({logical statement}):
          {do something}
        else:
          {do something different}
      
for example:

        a = 5
        if (a == 5):
          print("a is equal to 5")
        else:
          print("a is not equal to 5")
      
which should print:

        a is equal to 5
      
Now change the value of a and check that it prints out the correct output.
Hide Notes ▼

The Logical Operators

You will have noticed the double equal signs in the statement:


            if (a == 5):
          
This is because the single equal ("=") is an assignment statement; it assigns the value of whatever is on the right of the = to the variable named on the left. The double equal signs ("==") on the other hand, is a logical test. It checks to see if what is on the left is equal to what is on the right, and returns either True or False. We can see the difference between the two in the code:

            a = 5
            print(a)
            print(a == 5)
            print(a == 6)
          
which results in:

            5
            True
            False
          

Logical/Comparison Operators

Operator Test
==Equal To
!=Not Equal To
< Less Than
> Greater Than
<= Less Than Or Equal To
>= Greater Than Or Equal To

Example

Light the first 10 lights (red) except for the 5th light, which should be green.

            import board
            import neopixel

            nPix = 20

            pixels = neopixel.NeoPixel(board.D18, nPix)

            for i in range(10):

              if (i == 4):
                pixels[i] = (0, 255, 0)
              else:
                pixels[i] = (255, 0, 0)
          

Exercises

1) Make all of the lights red, except for the 3rd one which should be blue.
Show Notes ▼
Show Solution ▼
2) Make all of the lights red, except for the 8th one which should be blue. HOWEVER, use a Not Equal To statement.