Hi
A simple if-and statement is not working and I would like to know why.
I have a simple white rectangle called rec. I want to change the fill color when it is clicked.
Here is the code I tried:
if mouse.isPressedIn(rec) and rec.fillColor == 'white':
rec.fillColor = 'red'
I also tried the following:
if mouse.isPressedIn(rec):
if rec.fillColor == 'white':
rec.fillColor = 'red'
I know that the following code works, but I don’t know why the above code is not working
what does it mean the if-construction does not work? The if-expression never evaluates as “true” although you expect it to evaluate as true?
If
if mouse.isPressedIn(rec):
works, then the and-part is wrong. What value does rec.fillColor take in cases you expect the if-construction to be true? You could add a print-statement to find out:
Hello Jens
Thank you for your reply!
I think that I do not fully understand your answer.
When I click on the rectangle with the previous two codes the color (white) does not change.
I always see a white rectangle.
As you suggested, I tried to print the value of the rectangle when I press the mouse. The following value was printed: [1 1 1].
I adapted the code (e.g. instead of “white” I wrote “[1 1 1]”, the same I did with red) and I still have the same problem that the color of the rectangle is still white.
Do have another suggestion for me what I can change in my code?
Thank you very much!
Mark
Hello Jens
Unfortunately, the code does not work. I get a invalid syntax error and the information “Experiment ended with exit code 1 [pid:16732]”. I also tried to exclude the third comma in [1,1,1,] but without success.
For me, too : ). Thank you very much!
Only an additional short question, what does .all() in this context mean? (why is re.fillColor == white not enough?)
as I wrote earlier, fillColor is a list. When you print the value of fillColor to the console, you see that it has always the structure [x, y, z]. So, it is a list. When you compare a list, you have to compare any or all list-elements. Therefore you need a.all() or a.any() (a = your list).
white is just a variable, you could write
(rec.fillColor == [1, 1, 1]).all()
instead. It is just easier to read IMHO than [1, 1, 1].
Behind the scenes, fillColor is a Color object which supplies it’s own value in the correct color space when accessed. The object itself knows how to do comparisons to strings and lists and etc. so you can also do:
rec._fillColor == "red"
(_fillColor is the behind-the-scenes object from which fillColor is accessed)