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.
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
Operator | Test |
---|---|
== | Equal To |
!= | Not Equal To |
< | Less Than |
> | Greater Than |
<= | Less Than Or Equal To |
>= | Greater Than Or Equal To |
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)
Solution: To light up the last 5 lights (green) use:
import board
import neopixel
nPix = 20
pixels = neopixel.NeoPixel(board.D18, nPix)
for i in range(10):
if (i == 2):
pixels[i] = (0, 0, 255)
else:
pixels[i] = (255, 0, 0)